Read whole file in blocks in c#

Go To


I have a file from bank that is structure in very special way. Where there is account number (25), account balance start (60F), account balance stop (62F), and transactions (61 for transaction and 86 for this transaction details).


:86:723>00PRZELEW OTRZYMANY ELIXIR>20Fakt VAT 1 nr 00911/03
:86:723>32Firma XXXXXXXXXXă>33Krakow
:61: 0304030403DN1000,00S223NONREF//CENT30403H002342
:86:223>00PRZEL KRAJ MULTICASH>20000004020 20021224 Fa. 0095
:86:223>21007203-FIRMA SP. Z O>308510101010>311234567890123456
:86:723>00PRZELEW OTRZYMANY ELIXIR>20Fakt VAT 1 nr 00911/03
:86:723>32Firma XXXXXXXXXXă>33Krakow



It always has 2 lines of breaks between each block. I would like to put those blocks into an object that I create.

string[] test = File.ReadAllLines(file);
foreach (var s in test) {


How can I approach it the proper way? Normally I would go by foreach line and try to split the blocks by empty 2 lines then go further by doing multiple if/else statements. But maybe there's simple/better approach to this?

2012-04-03 20:15
by MadBoy
Some of the answers to this question will get you close - Dan Fitch 2012-04-03 20:23
You may want to look at this post - Darryl Braaten 2012-04-03 20:23
Ahhh, I just love these legacy formats. Even better when the lines aren't delimited but contain fixed-width fields in some arbitrary encoding.. - AKX 2012-04-03 20:25


string[] blocks = (file.ReadAllText(file)).split(new string[] {"\n\n\n"}, StringSplitOptions.None)

Should break it into blocks for you.

2012-04-03 20:22
by ClassicThunder
Ooooh, very good! Then you just blocks.Select(b->b.Split("\n") and get the blocks as string arrays - zmbq 2012-04-03 20:25
I like this approach, assuming that the file isn't massive as Tudor says it might be. If the file is small, use this approach (and re-split into lines later). If it's big, use Tudor's - Kevin Anderson 2012-04-03 20:25
It shouldn't be massive. 50 accounts, couple of transactions per day - MadBoy 2012-04-03 20:26
Only problem is Split takes char not a strin - MadBoy 2012-04-03 20:32
Sorry I couldn't remember the exact overload off the top of my head. Fixed and source to the overload I'm, using. - ClassicThunder 2012-04-03 20:35
@MadBoy: You can try to use the overload that takes an array of strings: string[] blocks = (file.ReadAllText(file)).split(new string[] {"\n\n\n"}, StringSplitOptions.None);Tudor 2012-04-03 20:37


Look at using StreamReader and use your logic to find what you are looking for.

StreamReader _sr = new StreamReader("YourFile");
2012-04-03 20:26
by Jmyster