Resolved file read and write

mrsoleil

New member
Joined
Apr 23, 2014
Messages
2
Programming Experience
Beginner
Hi Everyone,

I have a text file (test.txt) with random amount of lines where each line has 10 fields as shown below

i.e.: string1|string2|string3||string5|string6||||string10| (some fields are empty)

I would like to be able to convert each line into 15 fields and change some of the fields position along the line and output the result on a different file (test1.txt)

i.e.: string1|string2|||string5|||||string10|string3|string6|||| line = 15 fields, string3 now on field 11 and string6 now on field 12

Any input will be much appreciated

M
 
Last edited:

mrsoleil

New member
Joined
Apr 23, 2014
Messages
2
Programming Experience
Beginner
Hi,

I was able to do the following. May not be the best solution but it does the trick :)
using (var sourceFile = new StreamReader("C:\\test.txt"))
using (var destinationFile = new StreamWriter("C:\\test1.txt"))
{
    string line;

    while (!sourceFile.EndOfStream)
    {
        line = sourceFile.ReadLine();

        string[] fields = line.Split('|');

        line = string.Format("{0}|{1}|{2}||{4}|{5}||{7}|{8}|{9}|{10}|{3}|{6}||||", fields);
        destinationFile.WriteLine(line);
    }

    sourceFile.Close();
    destinationFile.Close();
}

Thank you

M.
 
Last edited by a moderator:

jmcilhinney

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
3,196
Location
Sydney, Australia
Programming Experience
10+
Seems pretty reasonable. There's no point closing the files manually though. The whole point of the 'using' statement is that the object will be disposed at the end of the block.
 
Top Bottom