Search code examples
c#arraysstringfile.readalllines

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


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.


Solution

  • 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 
    }