views:

70

answers:

3

Hi All,

I would really appreciate if somebody could help me/offer advice on this.

I have a file, probably about 50000 lines long, these files are generated on a weekly basis. each line is identical in terms of type of content.

original file:

address^name^notes

but i need to perform a switch. i need to be able to switch (on each and every line) the address with the name. so after the switch has been done, the names will be first, and then addresses and then notes, like so:

result file:

name^address^notes
+4  A: 

50,000 isn't that much these days, so simply reading in the whole file and outputting the wanted format should work fine for you:

string[] lines = File.ReadAllLines(fileName);
string newLine = string.Empty;

foreach (string line in lines)
{
    string[] items = line.Split(myItemDelimiter);
    newLine = string.Format("{0},{1},{2}", items[1], items[0], items[2]);
    // Append to new file here...
}
Oded
I would recommend against using the ReadAllLines route if there is any chance of growing or re-using this process, 50K lines can be a memory hog. Mick Walker's solution will ensure memory isn't un-necessarily used.
Mitchel Sellers
Fair comment, this indeed will not scale to very large files, and in that respect Mick Walker has a better solution.
Oded
A: 

Go go gadget REGEX!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static string Switcheroo(string input)
        {
            return System.Text.RegularExpressions.Regex.Replace
                (input,
                 @"^([^^]+)\^([^^]+)\^(.+)$",
                 "$2^$1^$3",
                 System.Text.RegularExpressions.RegexOptions.Multiline);
        }

        static void Main(string[] args)
        {
            string input = "address 1^name 1^notes1\n" +
                     "another address^another name^more notes\n" +
                     "last address^last name^last set of notes";

            string output = Switcheroo(input);
            Console.WriteLine(output);
            Console.ReadKey(true);
        }
    }
}
Juliet
"Go go gadget REGEX!" - I love the enthusiasm :)
Basiclife
lol me too +1 .
baeltazor
+4  A: 

How about this?

StreamWriter sw = new StreamWriter("c:\\output.txt");
        StreamReader sr = new StreamReader("c:\\input.txt");
        string inputLine = "";

        while ((inputLine = sr.ReadLine()) != null)
        {
            String[] values = null;
            values = inputLine.Split('^');
            sw.WriteLine("{0}^{1}^{2}", values[1], values[0], values[2]);
        }
        sr.Close();
        sw.Close();
Mick Walker
+1 for reading in stream
Yann Schwartz