Sign in to follow this  
Montynis

[.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 this post


Link to post
Share on other sites
string[] 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.

Share this post


Link to post
Share on other sites
Quote:
Original post by jpetrie
string[] 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.


Thanks for answer.

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

Hello
Bye
Good evening

How I could do that?

Share this post


Link to post
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 this post


Link to post
Share on other sites
Thanks for answers.

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 this post


Link to post
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());

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this