6

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
CJ7
  • 22,579
  • 65
  • 193
  • 321

3 Answers3

9

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.

Nimesh Madhavan
  • 6,290
  • 6
  • 44
  • 55
2

Documentation says that StreamWriter uses UTF8-Encoding by default.

Thorsten Dittmar
  • 55,956
  • 8
  • 91
  • 139
  • 2
    +1 Although it's UTF8 without BOM, so you might not realise!. http://msdn.microsoft.com/en-us/library/fysy0a4b.aspx – MarkJ Jun 12 '10 at 18:02
1

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.

  • 1
    Both your current answers link to the same site. If you are affiliated with this site, you should state it in your answer. –  Nov 28 '13 at 14:47
  • Thanks for informing me about this. Yes, I am affiliated with ezVB.net. – user3032129 Nov 28 '13 at 15:00