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
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:
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.The simplest way to do it is to use two double-quotes, back-to-back, which is how VB represents quotes in strings.
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:
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.