Wednesday, September 16, 2015

Reading a delimited text file in C#

You can of course write your own string parsing code or you can take the easy way and add a reference to Microsoft.VisualBasic within your Visual Studio project and make use of the TextFieldParser

This little snippet loads the content of a delimited text file into a ListView

using Microsoft.VisualBasic.FileIO;          private void loadCSVFile(string filePath, string delimiter) {     TextFieldParser tfParser = new TextFieldParser(filePath);     tfParser.TextFieldType = FieldType.Delimited;     tfParser.SetDelimiters(delimiter);     string[] curRow;     ListViewItem lvi;     while (!tfParser.EndOfData)     {         curRow = tfParser.ReadFields();         lvi = listView1.Items.Add(curRow[0]);         for (var ci = 1; ci < curRow.Length; ci++)         {             lvi.SubItems.Add(curRow[ci]);         }     }     tfParser.Close();     tfParser.Dispose(); }

Sometimes VB is your friend.


Usual caveats about production code (try/catch etc.)

No comments: