I want to extend a data collection in a .txt file.
I'm reading a .txt file into a string array. Then I'm making a new string array with 5 more elements.
string oldarray[] = File.ReadAllLines(targetfile); //it is correctly reading the file
string newarray[] = new string[oldarray.Count()+5];
for (int i = 0; i < oldarray.Count(); i++) { //copy old array into new bigger one
newarray[i] = oldarray[i];
}
newarray[oldarray.Count() + 1] = "Data1"; //fill new space with data
newarray[oldarray.Count() + 2] = "Data2";
newarray[oldarray.Count() + 3] = "Data3";
newarray[oldarray.Count() + 4] = "Data4";
newarray[oldarray.Count() + 5] = " "; //spacer
//now write new array into same textfile over old data
File.WriteAllLines(targetfile, newarray); //System.IndexOutOfRangeException
I also tried writing line by line to the file like so, but it did just spit out the same exception:
using (StreamWriter writer = new StreamWriter(destinationFile)) //System.IndexOutOfRangeException
{
for (int i = 0; i < newarray.Length; i++)
{
writer.WriteLine(newarray[i]);
}
}
Why does it do that, and how do I fix it?
Array indexes are zero-based so
oldarray.Count() + 5
points to an element after the end of the array. The first element is left empty too.This could be fixed by fixing the indexes to be between 0 and 4 instead of 1 and 5. A better solution though would be to load the lines as a list and append the new strings :
Or even
ReadAllLines
uses a List as well and returns a copy of the list as an array.ReadLines
on the other hand, returns lines one at a time as anIEnumerable<string>
. The file remains open as long as theIEnumerable
is iterated, so we needToList()
to consume it and allow the file to close before overwriting it.