Entering a C # text file to output multiple files

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 split a file into several files based on the first 6 characters starting at position 2.

File 1 with the name 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 with the name 9875D.asc:

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

I do not know what will be in the file before the program receives it, only the format. 6 digits will vary depending on the client. I do not know what they will be.

The only thing I know is the format.

Can someone give me a suggestion on how to dynamically receive / maintain this information so that I can parse it into separate files?

+6
source share
4 answers

Read line by line. Get the code from each line and create a file, put the link to the open file stream in the dictionary with the code as the key. On each next line, check the dictionary for the key and use an open stream or create a new one. After reading the entire file, close all streams.

This algorithm will not allow you to use too much memory for the lines of the file if it is large.

To parse each line, you can simply use RegEx, for example.

+1
source

I suggest using a parser of this class TextFieldParser .

You can read data in memory, sort it using the first field, and then write out individual files.

+4
source
 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 } 
+2
source

You can do it by brute force.

Reading:

 Dictionary<string, List<string>> DICT; Until End of File { Read a line to LINE Read characters 1-7 in LINE to CUSTOMERID DICT[CUSTOMERID].Add(LINE); } 

Record:

 foreach KeyValuePair entry in DICT { Create file with name entry.Key foreach string line in entry.Value { Write line to file line } } 
0
source

Source: https://habr.com/ru/post/888711/


All Articles