# [.net] Working with text files in .NET

## Recommended Posts

Hello, I have got a text file which looks like: Hello Bye I want to change it to (from C# code): Hello, John Bye, Richard So I want separate correct each line of file. How I could do that? Thanks in advance.

##### Share on other sites
lines now contains each line of the file, so lines[0] would be "Hello" and lines[1] would be "Bye" from your example. You can then manipulate the strings as needed and write the file back out, or whatever.

##### Share on other sites
Quote:
 Original post by jpetriestring[] lines = System.IO.File.ReadAllLines("someFileName.txt");lines now contains each line of the file, so lines[0] would be "Hello" and lines[1] would be "Bye" from your example. You can then manipulate the strings as needed and write the file back out, or whatever.

Now I am trying to add some extra lines to the file, for example:

Hello
Bye
Good evening

How I could do that?

##### Share on other sites
            string[] lines = System.IO.File.ReadAllLines(Application.StartupPath + "\\test.txt");            Array.Resize(ref lines, lines.GetLength(0) + 2);            lines[lines.GetUpperBound(0) - 1] = "new item";            lines[lines.GetUpperBound(0)] = "new item 2";            System.IO.File.WriteAllLines(Application.StartupPath + "\\test.txt", lines);

##### Share on other sites

I am quite new to .NET programming and I have got one more simple question: how to remove, for example, the second element from the line array?

##### Share on other sites
By this point it's probably easier just to create a List<string> (they are easier to manipulate). So, extending Machaira's example would give us:
// Read an array of strings and copy to a list:List<string> Lines = new List<string>(File.ReadAllLines(Path.Combine(Application.StartupPath, "test.txt")));// Append two lines:Lines.Add("new item");Lines.Add("new item 2");// Remove the second item:Lines.RemoveAt(1);// Write to disk, using ToArray method to convert list to array:File.WriteAllLines(Path.Combine(Application.StartupPath, "test.txt"), Lines.ToArray());

## Create an account

Register a new account