How to write to a file in Unicode in Vb.Net

CJ7 picture CJ7 · Jun 11, 2010 · Viewed 29.8k times · Source

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

Answer

Nimesh Madhavan picture Nimesh Madhavan · Jun 11, 2010

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.