Reading Lines in C#

I came across an interesting scenario today while I was building an application that required me opening a file, reading it line by line, and importing it into a dataset. The reason this was an interesting scenario is because there is data that belongs to a specific identifier on different lines.

My immediate reaction was to read the data line by line through Streamreader. However, I discovered that only certain data would get entered. While Streamreader works extremely well for loading an entire file, it doesn’t work quite well if you need to read each line individually. It was skipping lines as it read the file.

Microsoft itself provides a very useful guide for StreamReader, so I thought I’d throw it here:

using (StreamReader sr = new StreamReader("TestFile.csv")) 
            {
                string line;
                // Read and display lines from the file until the end of 
                // the file is reached.
                while ((line = sr.ReadLine()) != null) 
                {
                    Console.WriteLine(line);
                }
            }

Of course, each line had to be parsed, so I built an array:

using (StreamReader sr = new StreamReader("TestFile.csv")) 
            {
                string line;
                // Read and display lines from the file until the end of 
                // the file is reached.
                while ((line = sr.ReadLine()) != null) 
                {
                    string[] info = line.split(',');

                    string item = info[0];
                    string detector = info[1];
                    string result = info[2];
                }           
            }

I needed to look at the detector (info[1]) to determine which result (info[2]) accompanied the item (info[0]). A compilation of three detectors created a different result, so I needed to capture those.

The issue I ran into I mentioned previously: I couldn’t capture all the data. I discovered that I could parse the data using VisualBasic in C# (weird, I know). First, I had to Visual Basic as a reference from the References menu. Then, I needed to add Visual Basic:

Using Microsoft.VisualBasic.FileIO;

From there, I just needed to add these quick lines of code.

TextFieldParser parse = new TextFieldParser(@"C:\TestFile.csv");
parse.TextFieldType = FieldType.Delimited;
parse.SetDelimiters(",");
while (!parse.EndOfData) 
{
    //Processing row
    string[] info = parse.ReadFields();
    
    string item = info[0];
    string detector = info[1];
    string result = info[2];    
}
parse.Close();

This worked extremely well as it parsed every single line and gave me the data I needed. I hope this helps anyone else who comes across this problem.

Comments are closed.