强制的StreamWriter改变编码 [英] Forcing StreamWriter to change Encoding
问题描述
我想保存使用文件的DialogResult
和的StringBuilder
。使文字后,我打电话下面的代码保存文件:
I am trying to save a file using DialogResult
and StringBuilder
. After making the text, I am calling the following code to save the file:
if (dr == DialogResult.OK)
{
StreamWriter sw = new StreamWriter(saveFileDialog1.FileName);
sw.Write(sb.ToString());
sw.Close();
}
我想第二个参数添加到的StreamWriter
为 Encoding.UTF8
但由于第一个参数是字符串
而非流
,它并没有对其进行编译。
I tried to add the second parameter to StreamWriter
as Encoding.UTF8
but since the first argument is a string
rather than a Stream
, it does not compile it.
我怎么能说字符串转换为流能够通过第二个参数作为编码?
How can I convert that string to a stream to be able to pass the second parameter as Encoding?
这样做的原因是,地方在我的文字我有μ
但是当文件保存它显示了像μ
所以μ
越来越起子!
The reason for this, is that somewhere in my text I have µ
but when the file is saved it shows like μ
so the µ
is getting screwd!
感谢
推荐答案
只是把它包在的FileStream
。
StreamWriter sw = new StreamWriter(
new FileStream(saveFileDialog1.FileName, FileMode.Open, FileAccess.ReadWrite),
Encoding.UTF8
);
如果您想追加,使用 FileMode.Append
代替。
If you want to append, use FileMode.Append
instead.
您也应该调用的Dispose()
在尝试/终于
块,或使用使用
块处置的对象,当它超过了使用
范围
You should also call Dispose()
on a try/finally
block, or use a using
block to dispose the object when it exceeds the using
scope:
using(
var sw = new StreamWriter(
new FileStream(saveFileDialog1.FileName, FileMode.Open, FileAccess.ReadWrite),
Encoding.UTF8
)
)
{
sw.Write(sb.ToString());
}
这会正常关闭和处理所有异常路径的数据流。
This will properly close and dispose the streams across all exception paths.
这篇关于强制的StreamWriter改变编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!