How to: Add a string to a string array using File.ReadAllLines

933 Views Asked by At

How to: Add a string to a string array using File.ReadAllLines

I think the question is clear: I want to add a new string to an existing string array, which gets ist content from a File.ReadAllLines.

public void CreateNewFolder()
{
    string[] lines = File.ReadAllLines(stringFile, Encoding.UTF8);
    lines[lines.Length + 1] = "Test";
    File.WriteAllLines(stringFile, lines, Encoding.UTF8);
}

The index of the array is "too small", but I do not know why.

2

There are 2 best solutions below

9
On BEST ANSWER

The error is caused since the length of the array is fixed and the and the last index (where you wanna add the new item) is always outside the array. You can use a list instead:

public void CreateNewFolder()
{
    List<String> lines = File.ReadAllLines(stringFile, Encoding.UTF8).ToList();
    lines.Add("Test");
    File.WriteAllLines(stringFile, lines.ToArray(), Encoding.UTF8);
    //Calling the ToArray method for lines is not necessary 
} 
0
On

You get the error because you try to change an item beyond current array length. You can use Array.Resize<T> to resize array first and then change last item

public void CreateNewFolder()
{
    string[] lines = File.ReadAllLines(stringFile, Encoding.UTF8);
    Array.Resize(ref lines, lines.Length + 1);
    lines[lines.Length - 1] = "Test";
    File.WriteAllLines(stringFile, lines, Encoding.UTF8);
}