thompogi
thompogi

Reputation: 39

convert vertically listed strings of a text file to horizontal format

I have a text file "Test 2.txt" with the below format:

string1
string2
string3
string4
string5
string6
string7
string8
string9
...and so on...

I would like to convert it to text file "Test.txt" with below format:

string1,string2,string3
string4,string5,string6
string7,string8,string9
...and so on...

My code at the moment is below:

string line;
string DatabaseFullPath = @"C:\Test2.xsr";

using (var file = new StreamReader(DatabaseFullPath, Encoding.UTF8))
{
    int count = File.ReadLines(DatabaseFullPath).Count();

    while ((line = file.ReadLine()) != null)
    {
        count++;
        if (count % 3 == 0)
        {
            using (StreamWriter writetext = new StreamWriter(@"D:\Test.txt"))
            {
                writetext.WriteLine(line + '\n');
            }
        }
        else
        {
            using (StreamWriter writetext = new StreamWriter(@"D:\Test.txt"))
            {
                writetext.Write(line + ',');
            }
        }
    }
}

It seems that the StreamWriter is just overwriting each string "line" with another string "line" but I am not sure about it.

Upvotes: 1

Views: 620

Answers (1)

NetMage
NetMage

Reputation: 26926

string DatabaseFullPath = @"C:\Test2.xsr";

using (var file = new StreamReader(DatabaseFullPath, Encoding.UTF8)) {
    using (StreamWriter writetext = new StreamWriter(@"D:\Test.txt")) {
        int count = 0;
        string line;
        while ((line = file.ReadLine()) != null) {
            if (++count % 3 == 0)
                writetext.WriteLine(line);
            else
                writetext.Write(line + ',');
        }
    }
}

Upvotes: 1

Related Questions