Jham Jham - 4 months ago 17
Vb.net Question

NON QUOTATION MARK IN CSV FILE BUT IN TXT FILE IT HAVE

Hi the below code was my code in creating csv file. The creation of csv is alright but when the csv convert to text file they sey it should have quotation mark between the beginning and in the end of the value. EX: in CSV File the value was: Jham, and in the textfile it should be : "Jham" - how can i manage it? can someone help?

listofValue = ZipFileStr & "," & Img1Val & "," & Img2Val & "," & RExVal & "," & BundleNo & "," & BundleNo & "," & URNVal & "," & PromocodeVal & "," & ZipFileStore & "," & SNumVal & "," & DpackVal & "," & ArrivalDate & "," & CompleteDateTwo & "," & KidPCVal & "," & MDBName

Dim PathX As String = TempPath & "\"

If Not IO.Directory.Exists(PathX) Then
MkDir(PathX)
End If

Dim sampleX As String = PathX & ZipFileStr & "P.csv"
Dim outFile As IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(sampleX, True)

outFile.WriteLine(listofValue)
outFile.Close()

Answer

Firstly, when posting code snippets, please format them for readability. I have fixed that for you.

Secondly, there's no such thing as "converting" between a CSV file and a text file. A CSV is just plain text. If the text contains record and field delimiters then it is a CSV file, otherwise it's not. It's plain text either way.

As for the question, I would suggest writing a CSV with quoted values something like this:

Dim line = String.Format("""{0}"",""{1}"",""{2}""",
                         firstValue,
                         secondValue,
                         thirdValue)

The use of String.Format or, in VB 2015, string interpolation makes the code far more readable. As for putting a double-quote in a literal string, you simply escape it with another double-quote. You might also use the ControlChars.Quote field:

Dim line = String.Format("{0}{1}{0},{0}{2}{0},{0}{3}{0}",
                         ControlChars.Quote,
                         firstValue,
                         secondValue,
                         thirdValue)

Note that it is generally only text values that get quoted, not numbers and dates and the like. That's because the main reason for the quoting is to allow a value to contain delimiters, i.e. commas or line breaks. If none of your values do contain delimiters then you can safely omit the quotes altogether.