skip to Main Content

Here is my vb.net code using visual studio 2019 community edition

dim A as string    
dim B as string    
dim C as string    
A="GST"    
B="B2B"    
C="N"

wr = New StreamWriter("D:test.txt")    
wr.WriteLine(String.Format("{0},{1},{2}", A, B, C)    
wr.Flush()

But the output comes in text file like this

GST, B2B, N

I want to add double quotes like this

"GST","B2B","N"

but the code must be in vb.net

Anyhelp can be appreciated

Thanks

2

Answers


  1. You could extend the StreamWriter class to provide custom formatting of the strings you need to write to your CSV file.

    Here, four new methods are added to the StreamWriter, allowing to pass a collection of strings that should be quoted, or a collection of strings where only some members should be quoted. A companion array of Boolean values defines which members are quoted. Of course, you could devise a different method to mark quoted elements, as using a prefix / suffix etc. with little changes.

    If you don’t want to use the double-quote char (", ChrW(34)), you can pass a different char to the methods.

    You can call the extension methods as:

    Dim csvPath = [The path of the CSV file]
    
    ' All elements are quoted
    Using writer As New StreamWriter(csvPath)
        writer.WriteQuoted({"First", "Second", "Third"})
    End Using
    
    ' All elements are quoted. Async version, using single quote
    Using writer As New StreamWriter(csvPath)
        Await writer.WriteQuotedAsync({"First", "Second", "Third"}, "'"c)
    End Using
    
    ' Some elements are quoted
    Using writer As New StreamWriter(csvPath)
        writer.WriteQuotedAndUnquoted({"First", "Second", "Third"}, {True, False, True})
    End Using
    

    Extension method:
    If you don’t know how Extension methods work, just add a Module to the Project (here, named ExtensionMethods) and paste in the code that follows. Rebuild the Project after.

    Imports System.IO
    Imports System.Runtime.CompilerServices
    
    Module ExtensionMethods
        <Extension()>
        Public Sub WriteQuoted(writer As StreamWriter, values As String(), Optional quote As Char = ChrW(34))
            Dim quotedValues = String.Join(",", values.Select(Function(v) $"{quote}{v}{quote}"))
            writer.WriteLine(quotedValues)
        End Sub
    
        <Extension()>
        Public Async Function WriteQuotedAsync(writer As StreamWriter, values As String(), Optional quote As Char = ChrW(34)) As Task
            Dim quotedValues = String.Join(",", values.Select(Function(v) $"{quote}{v}{quote}"))
            Await writer.WriteLineAsync(quotedValues)
        End Function
    
        <Extension()>
        Public Sub WriteQuotedAndUnquoted(writer As StreamWriter, values As String(), quoted As Boolean(), Optional quote As Char = ChrW(34))
            If values.Length <> quoted.Length Then Throw New ArgumentException("Elements count mismatch")
            Dim quotedValues = String.Join(",", values.Select(Function(v, i) If(quoted(i), $"{quote}{v}{quote}", v)))
            writer.WriteLine(quotedValues)
        End Sub
    
        <Extension()>
        Public Async Function WriteQuotedAndUnquotedAsync(writer As StreamWriter, values As String(), quoted As Boolean(), Optional quote As Char = ChrW(34)) As Task
            If values.Length <> quoted.Length Then Throw New ArgumentException("Elements count mismatch")
            Dim quotedValues = String.Join(",", values.Select(Function(v, i) If(quoted(i), $"{quote}{v}{quote}", v)))
            Await writer.WriteLineAsync(quotedValues)
        End Function
    End Module
    
    Login or Signup to reply.
  2. The simplest way to do it is to use two double-quotes, back-to-back, which is how VB represents quotes in strings.

    wr.WriteLine(String.Format("""{0}"",""{1}"",""{2}""", A, B, C)
    

    I inserted two double-quotes before and after each placeholder. There are three at the beginning and end of the string because those are the original double-quotes that are necessary for all literal strings.

    Unless this is for a class, where you have to use String.Format(), I prefer to use plain ol’ string concatenation, like so:

    wr.WriteLine("""" & A & """,""" & B & """,""" & C & """")
    

    For what it’s worth, CSV’s don’t require double-quotes, unless the string contains special characters that have meaning in a CSV, such as commas, quotes, or new lines.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search