0

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

2 Answers 2

3

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 
} 
Sign up to request clarification or add additional context in comments.

9 Comments

You might want to add to your answer that he gets the error because an array has a fixed length once defined. List is the way to go. +1
There is no definition for ToList().
@middelpat: Good suggestion, will add it
@Exception include "using System.Linq;"
Final answer! Perfect. Thank you very much!
|
0

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.