Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
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();"

C#
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.
C#
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:
C#
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
Posted
Updated 4-Apr-18 3:23am
Comments
Christiaan van Bergen 3-Apr-18 16:06pm    
The error: "System.IndexOutOfRangeException: Index was outside the bounds of the array" lets me believe that that are not sufficient lines in your config.txt file. Because, without checking the amount of lines, you are trying to access the lines in the array. Could you check that, or maybe even share the contents of that config.txt file?
mygearstationcom 3-Apr-18 16:40pm    
I can use the same config.txt file that I am creating via the WriteAllText when I comment out the createSSMonitorSubDirectories(); line in the MainForm routine. My problem occurs when I write the config.txt and then try to read from it immediately there after. I agree with both responses that "It's an index issue"
Here's the contents of config.txt:
IP Address: 012.345.678.901
Device Port: 1111
Log Directory: Saved\
Config Directory: config\
Enter Modules here.

Will searching the term "C# how to reset index after WriteAllText" on the internet get me closer to solving this issue? Or do I need to look elsewhere? It seems to me that the error message that I'm getting can be caused my many many things.
Christiaan van Bergen 3-Apr-18 18:29pm    
I don't think it has to do with WriteAllText. You have a config.txt file with only 5 lines. But you are trying to read lines 7 and 8. Really, I think that's your issue with this code. It is the line: var trimmedCD = lines[6].TrimStart(trimConfigDirectory.ToCharArray());
mygearstationcom 4-Apr-18 1:25am    
Thanks for your tolerance and great answers. I see what you mean. I also see why I was needing to read even number lines. It was due to splitting the lines.

Would a solution be to add more lines so the total is greater than 8 lines? Will the code then work during the startup of my program?

I'll try this tomorrow to see how it works.

Thanks again.

This error is telling you that you are accessing an index that doesn't exist. Remember that arrays in C# start at 0 so if you wanted the 4th line, you would use 3 as the index number.
 
Share this answer
 
Comments
mygearstationcom 3-Apr-18 16:42pm    
Thanks. Please see my comment on other response. I'm thinking that I need to understand how to reset the index. I'm thinking that when I write I get to the end. I then read starting at that point thus the error. Should my question be: "How do I reset the index back to the beginning?"
The error went away after modifying my code as follow:
C#
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.\nEnter Modules here.\nEnter Modules here.\n");
	System.IO.File.WriteAllText(@"config\config.txt", defaultText);


Thanks for the great response.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900