We help IT Professionals succeed at work.

ASP.Net - Easy question CSV read comma

sbornstein2 used Ask the Experts™
Hello all,

I have the following code and the split is finding the extra comma it looks like in the row like this how do I handle this.  File has 9 columns 0-8  Row example:

[2]: "AE,1,VARIABLE,ID,SD0058,\"Variable appears in dataset, but is not in SDTM standard\",Metadata,Warning,"

Code is:
  // create new datatable
        DataTable dt = new DataTable();

        // get the column header means first line
        string[] temp = str[0].Split(',');

        // creates columns of gridview as per the header name
        foreach (string t in temp)
            dt.Columns.Add(t, typeof(string));

        // now retrive the record from second line and add it to datatable
        for (int i = 1; i < str.Length; i++)
            string[] t = str[i].Split(',');

Open in new window

Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
you have commas inside your quoted fields. Two choices -- choose a different field separator or use a regex.

Here is an example of the latter:
        string contents = System.IO.File.ReadAllText("e:\\feeds\\test.csv");

            dynamic lines = contents.Split(new string[] { "\r\n" }, StringSplitOptions.None);
            for (int i = 0; i < lines.Length; i++)

                Regex regx = new Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");
                String[] parts = regx.Split(lines[i]);

                for (int p = 0; p < parts.Length; p++)

                    parts[p] = parts[p].Trim(' ', '"');


Open in new window

from: http://forums.asp.net/t/1803616.aspx/1
kaufmedGlanced up at my screen and thought I had coded the Matrix...  Turns out, I just fell asleep on the keyboard.
Most Valuable Expert 2011
Top Expert 2015