George Powell George Powell - 1 month ago 8
C# Question

How do I read and edit a .txt file in C#?

For example, I have a txt file that reads:

12 345 45
2342 234 45 2 2 45345
234 546 34 3 45 65 765
12 23 434 34 56 76 5


I want to insert a comma between all the numbers, add a left brace to the begining of each line and a right brace to the end of each line. So after the editing it should read:

{12, 345, 45}
{2342, 234, 45, 2, 2, 45345}
{234, 546, 34, 3, 45, 65, 765}
{12, 23, 434, 34, 56, 76, 5}


How do I do it?

Answer

I pretty much figured it out while you were all giving me your answers, but thanks a lot anyway :). I came up with this:

TextReader reader = new StreamReader("triangle.txt");
TextWriter writer = new StreamWriter("triangle2.txt");
for (; ; )
{
    string s = reader.ReadLine();
    if (s == null)
       break;
    s = s.Replace(" ", ", ");
    s = "{" + s + "},";
    writer.WriteLine(s);
}