Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading delimited text file?

Tags:

c#

.net

io

I am trying to read from a delimited text file, but everything is returned in in one row and one column.

My connections string is

OleDbConnection con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
    Path.GetDirectoryName(@textBox1txtPath.Text) + ";" + 
    "Extended Properties=\"text;HDR=YES;IMEX=1;Format=Delimited(|)\"");

And my text file reads:

ItemNumber|ProductStatus|UPC
0000012|closed|2525

Please assist

like image 365
user2686400 Avatar asked Sep 11 '13 12:09

user2686400


1 Answers

Okay, so one option would be to take a different approach. Consider the following code:

// read the entire file and store each line
// as a new element in a string[]
var lines = File.ReadAllLines(pathToFile);

// we can skip the first line because it's
// just headings - if you need the headings
// just grab them off the 0 index
for (int i = 1; i < lines.Length; i++)
{
    var vals = lines[i].Split('|');

    // do something with the vals because
    // they are now in a zero-based array
}

This gets rid of that monstrosity of a connection string, eliminates the overhead of an Odbc driver, and drastically increases the readability of the code.

like image 82
Mike Perrenoud Avatar answered Sep 19 '22 04:09

Mike Perrenoud