CJ7
CJ7

Reputation: 23275

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

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

Upvotes: 6

Views: 34972

Answers (3)

user3032129
user3032129

Reputation: 31

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.

Upvotes: 1

Thorsten Dittmar
Thorsten Dittmar

Reputation: 56697

Documentation says that StreamWriter uses UTF8-Encoding by default.

Upvotes: 2

Nimesh Madhavan
Nimesh Madhavan

Reputation: 6318

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.

Upvotes: 9

Related Questions