C# spliting a String from Readline

December 21, 2007 at 07:39:36
Specs: Windows XP, 512

Im trying read in data from textfile into seperate string variables using a StreamWriter. I used readLine() to store each line, and substring to split into seperate fields. It works ok for the first line but I am having a problem with the 2nd line because one of variables is a different length and I am unsure how to solve this.
After opening the file, my for loop does the following:
for (; ; )
buffer = Convert.ToString(sr.ReadLine());

if (buffer == null) break;
tempitemnumber = buffer.Substring(0, 6);
i = tempitemnumber.Length;

tempcode = buffer.Substring(i, 4);
i += tempcode.Length;

tempdescription = buffer.Substring(i, 18);
i += tempdescription.Length;

tempprice = buffer.Substring(i, 7);
i += tempprice.Length;

tempunit = buffer.Substring(i, 3);
i += tempunit.Length;

tempcost = buffer.Substring(i, 6);
i += tempcost.Length;

tempCF = buffer.Substring(i, 4);
i += tempCF.Length;

tempgroup = buffer.Substring(i, 6);
i += tempgroup.Length;

tempsortcode = buffer.Substring(i, 7);
i += tempsortcode.Length;

tempbuyingterm = buffer.Substring(i, 3);

//debugs to show what was input into the variables


I have also noticed when I do a subtring it captures the "/t" tab characters from the textfile.

Is there an easier way of reading data seperately from textfiles? I've only just started familiarising must with C#, I am used to programming in C or C++, so it like a new world to me!
Substring is only method I have found that works. Is it not possible to use .Read() or .ReadBlock() instead of Readline(). Please could you recommend a simplier way for read/writing text files. Lol I think I I should buy a C# book after Christmas, I have wasted a lot of time on google and getting nowhere fast heh.


See More: C# spliting a String from Readline

Report •

December 21, 2007 at 19:38:30

Thanks for the code. It would also be useful to see examples of the data.

I think you want to try using regular expressions to break up the line into fields (instead of substring).

Look at docs for:

using System.Text.RegularExpressions;


Report •

December 21, 2007 at 19:53:34

Report •

Related Solutions

Ask Question