Click here to Skip to main content
15,891,657 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
static void lineChanger(string newText, string fileName, int line_to_edit)
        {
            string[] arrLine = File.ReadAllLines(fileName);
            arrLine[line_to_edit - 1] = newText;
            File.WriteAllLines(fileName, arrLine);
        }


lineChanger(textBox5.Text, "C:\\Users\\x\\Documents\\Random.txt", counter);
            lineChanger(textBox1.Text, "C:\\Users\\x\\Documents\\Random.txt", counter + 1);
            lineChanger(textBox2.Text, "C:\\Users\\x\\Documents\\Random.txt", counter + 2);
            lineChanger(textBox3.Text, "C:\\Users\\x\\Documents\\Random.txt", counter + 3);


I get the error "
Index was outside the bounds of the array.
" when trying to edit a line.

What I have tried:

I've tried changing the array from -1 but to no affect
Posted
Updated 13-Mar-22 8:09am
Comments
Richard MacCutchan 13-Mar-22 12:53pm    
Which file are you processing, how many lines does it contain and what is the value of counter when the error occurs?
Maciej Los 13-Mar-22 13:55pm    
What value counter variable holds?
PIEBALDconsult 14-Mar-22 1:00am    
You may also prefer to use verbatim strings for file paths.

1 solution

The reason is quite obvious. See updated procedure.
C#
static void lineChanger(string newText, string fileName, int line_to_edit)
{
    string[] arrLine = File.ReadAllLines(fileName);
	Console.WriteLine($"arrLine.Length: {arrLine.Length}\tline_to_edit: {line_to_edit}");
    if(line_to_edit < 0 || line_to_edit > arrLine.Length-1)
		{
			Console.WriteLine($"Note: line to edit ({line_to_edit}) is bigger than number of lines ({arrLine.Length}) in file or less than 0");
			return;
		}
	arrLine[line_to_edit] = newText;
    File.WriteAllLines(fileName, arrLine);
}


BTW:
Do not use "C:\\Users\\x\\Documents\\Random.txt" several times. Create and use a variable, for example:
C#
string sFile = "C:\\Users\\x\\Documents\\Random.txt";
//then
lineChanger(textBox5.Text, sFile, counter);
 
Share this answer
 
v3
Comments
CPallini 14-Mar-22 4:41am    
5.
Maciej Los 14-Mar-22 5:36am    
Thank you, Carlo.

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