Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Text File Input Multi-File Output

I have a file that looks something like this:

|29923C|SomeGuy,NameHere1     |00039252|042311|Some Address Info Here |
|47422K|SomeGuy,NameHere2     |00039252|042311|Some Address Info Here |
|98753D|SomeGuy,NameHere3     |00039252|042311|Some Address Info Here |
|29923C|SomeGuy,NameHere4     |00039252|042311|Some Address Info Here |
|47422K|SomeGuy,NameHere5     |00039252|042311|Some Address Info Here |

I need to break the file up into multiple files based on the first 6 characters starting in position 2.

File 1 named 29923c.asc:

|29923C|SomeGuy,NameHere1     |00039252|042311|Some Address Info Here |
|29923C|SomeGuy,NameHere4     |00039252|042311|Some Address Info Here |

File 2 named 47422K.asc:

|47422K|SomeGuy,NameHere5     |00039252|042311|Some Address Info Here |
|47422K|SomeGuy,NameHere2     |00039252|042311|Some Address Info Here |

File 3 named 9875D.asc:

|98753D|SomeGuy,NameHere3     |00039252|042311|Some Address Info Here |

I don't know what will be in the file before the program gets it, just the format. The 6 digits will change depending on the customer. I don't know what they will be.

The only thing I know is the format.

Can anyone give me a suggestion as to how to dynamically obtain\maintain this information so that I can parse it out into individual files?

like image 212
ErocM Avatar asked May 21 '11 16:05

ErocM


2 Answers

I suggest using a parser such a the TextFieldParser class.

You could read the data into memory, sort it using the first field then write out individual files.

like image 82
Oded Avatar answered Oct 17 '22 12:10

Oded


List<string> lines ; // load lines form file

Dictionary<string,List<string>> dic = new Dictionary<string,List<string>>();
foreach(string line in lines) 
{
    string key = line.Split('|')[0];

    if(!dic.ContainsKey(key))
        dic.Add(key,new List<string>{line});
    else 
        dic[key].Add(line) 
}

foreach(var pair in dic) 
{
    //create file and store there pair.Value   
}
like image 25
Stecya Avatar answered Oct 17 '22 11:10

Stecya