Navneet Duggal
Navneet Duggal

Reputation: 91

How to read data via streamreader from csv file as it is.. means it should come as string

I am reading csv file via streamreader. Issue is that in csv file if if the data is like "Read" then steamreader the same data is coming as ""Read"". How to remove this extra inverted commas?

Upvotes: 0

Views: 7162

Answers (1)

Tim
Tim

Reputation: 28530

It sounds like you're dealing with a CSV that has some (or all) of its fields quoted. If that's the case, I'd recommend using the Microsoft.VisualBasic.FileIO.TextFieldParser (which a lot of people don't seem to know about, and yes despite the namespace it can be used with C#).

Imports Microsoft.VisualBasic.FileIO.TextFieldParser;

Dim csvString As String = "25,""This is text"",abdd,""more quoted text"""

Dim parser as TextFieldParser = New TextFieldParser(New StringReader(csvString))

' You can also read from a file
' Dim parser As TextFieldParser = New TextFieldParser("mycsvfile.csv")

parser.HasFieldsEnclosedInQuotes = True
parser.SetDelimiters(",")

Dim fields As String()

While Not parser.EndOfData

    fields = parser.ReadFields()

    For Each (field As String in fields)
        Console.WriteLine(field)
    Next
End While

parser.Close()

The output should be:

25
This is text
abdd
more quoted text

Microsoft.VisualBasic.FileIO.TextFieldParser

To Import this, you'll need to add a reference to Microsoft.VisualBasic to your project.

Upvotes: 2

Related Questions