如何在 Vb.Net 中以 Unicode 格式写入文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3021684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 14:54:58  来源:igfitidea点击:

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

vb.netunicodestreamwriter

提问by CJ7

How should I modify the following Vb.Net code to write strto the file in unicode?

我应该如何修改以下 Vb.Net 代码以str使用 unicode写入文件?

Do I need to convert strto Unicodebefore writing to the file?

在写入文件之前是否需要转换strUnicode

Using sw As StreamWriter = New StreamWriter(fname)
    sw.Write(str)
    sw.Close()
End Using

回答by Nimesh Madhavan

Use the overriden constructorto 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.

根据您的要求选择 UTF8(8 位)或 Unicode(16 位)字符集编码。

回答by Thorsten Dittmar

Documentation says that StreamWriteruses UTF8-Encoding by default.

文档说StreamWriter默认情况下使用 UTF8 编码。

回答by user3032129

The below code explicitly instructs to save as UTF-8 without BOM.

下面的代码明确指示保存为没有 BOM 的 UTF-8。

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.

有关完整文档,请参阅www.ezVB.net