How to write to a file in Unicode in Vb.Net
-
26-09-2019 - |
Question
How should I modify the following Vb.Net code to write str
to the file in unicode?
Do I need to convert str
to Unicode before writing to the file?
Using sw As StreamWriter = New StreamWriter(fname)
sw.Write(str)
sw.Close()
End Using
Solution
Use the overriden constructor to specify the encoding
Using sw As StreamWriter = New StreamWriter(fname, true, System.Text.Encoding.Unicode)
sw.Write(str)
sw.Close()
End Using
Pick either UTF8(8bit) or Unicode(16 bit) character-set encoding as per your requirements.
OTHER TIPS
Documentation says that StreamWriter
uses UTF8-Encoding by default.
The below code explicitly instructs to save as UTF-8 without BOM.
Dim utf8WithoutBom As New System.Text.UTF8Encoding(False)
Dim orfWriter As System.IO.StreamWriter = New System.IO.StreamWriter(fileName, append, utf8WithoutBom)
orfWriter.Write(saveString)
orfWriter.Close()
For full documentation, see www.ezVB.net.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow