Reading a CSV where comma's are interpreted as newlines.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Fuzz13
    New Member
    • Jun 2010
    • 110

    Reading a CSV where comma's are interpreted as newlines.

    I'm writing a program that reads in a text file or a csv and for each line of text in the file it creates a new object of an aray:

    Code:
                    string[] lines = File.ReadAllLines(@newobject.csvDirectory);
    What I need to do is tell my code that if it encounters a comma that it needs to treat it as a new line marker. "\n"

    At first I thought I would run a replace statement saying

    Code:
    line[i].replace(",","\n");
    but it is putting in a literal "\n" which is kicking out illegal char errors. How do I tell my test that if there is a comma consider it a new line?

    That way a line like this:

    Code:
    This is line 1,This is line 2, This is line3. And more 3.
    will create 3 objects in my array.

    Thanks in advance.
  • Christopher Nigro
    New Member
    • Jul 2010
    • 53

    #2
    Use a StreamReader and call its ReadToEnd method to get a string. Then split that string on a comma to get your string array.

    Comment

    • Fuzz13
      New Member
      • Jun 2010
      • 110

      #3
      I'm confused as to how I read the data, split the data at the comma's, then have it reread everything with the newlines at commas made so it creates the appropriate number of objects in the array.

      Comment

      • Christopher Nigro
        New Member
        • Jul 2010
        • 53

        #4
        Something like this:

        Code:
        string[] lines = null;
        
         using (StreamReader sr = new StreamReader(@"..\..\Sample.txt"))
        {
            string fileContents = sr.ReadToEnd();
            lines = fileContents.Split(new char[]{','}, StringSplitOptions.RemoveEmptyEntries);
         }
        Last edited by Christopher Nigro; Jul 12 '10, 07:27 PM. Reason: formatting

        Comment

        Working...