I have a main form that opens a child form. I have a routine in the MainForm.cs to create 2 subdirectories and 1 text file. In the declaration of MainForm(), I added code to run my function "createSSMonitorSubDirectories();"
void createSSMonitorSubDirectories()
{
if (!System.IO.Directory.Exists(@"Saved"))
{
System.IO.Directory.CreateDirectory(@"Saved");
}
if (!System.IO.Directory.Exists(@"config"))
{
System.IO.Directory.CreateDirectory(@"config");
if(!System.IO.File.Exists(@"config\config.txt"))
{
var configFile = System.IO.File.Create(@"config\config.txt");
configFile.Close();
string defaultText = ("IP Address: 012.345.678.901\r\nDevice Port: 1111\r\nLog Directory: Saved\\\r\nConfig Directory: config\\\r\nEnter Modules here.\r\n");
System.IO.File.WriteAllText(@"config\config.txt", defaultText);
}
}
}
I have a button when clicked shows the child dialog.
void ConfigbuttonClick(object sender, EventArgs e)
{
var ccf = new configConnection();
ccf.ShowDialog(this);
}
With the above code, I get program shutdown with the following message:
System.IndexOutOfRangeException: Index was outside the bounds of the array.
at SS_BusMonitor.configConnection.fillInConfigForm()
The fillInConfigForm() is ran as soon as the child form is activated. Here's the code:
void fillInConfigForm()
{
try{
string[] lines = System.IO.File.ReadAllLines(@"config\config.txt");
var trimCharsIP = "IP Address:";
var trimmedIP = lines[0].TrimStart(trimCharsIP.ToCharArray());
deviceIPAddress.Text = trimmedIP;
var trimCharsPort = "Device Port:";
var trimmedPort = lines[2].TrimStart(trimCharsPort.ToCharArray());
devicePortNumber.Text = trimmedPort;
var trimLogDirectory = "Log Directory:";
var trimmedLD = lines[4].TrimStart(trimLogDirectory.ToCharArray());
logDirectory.Text = trimmedLD;
var trimConfigDirectory = "Config Directory:";
var trimmedCD = lines[6].TrimStart(trimConfigDirectory.ToCharArray());
configDirectory.Text = "C:" + trimmedCD;
for(int i = 8; i < lines.Length; i++)
{
string nextLine = (lines[i]);
this.moduleNamesList.Text += nextLine + "\n";
}
}
catch (ArgumentNullException e2)
{
MessageBox.Show("Load Config Defaults: " + e2.Message, "SS Bus Monitor",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
What I have tried:
When I comment out all code in the try statement, the child form shows and I can edit and save its fields. Additionally, when I comments out the MainForm's statement and have subdirectories and the config.txt file then all works as designed.
I have read all other similar errors but none seem to be my issue. I've spent nearly 6 hours reading, searching and looking for solutions. Please guide me to an answer.
I think I need to re-initialize with a new statement but I have run out of ideas. Any suggestions? It seems to be a conflict between the WriteAllText and the ReadAllLines. Am I thinking correctly? What is the "fix"?
TIA