Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
444 views
in Technique[技术] by (71.8m points)

c# - Forcing StreamWriter to change Encoding

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();
    }

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!

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Just wrap it in a FileStream.

StreamWriter sw = new StreamWriter(
    new FileStream(saveFileDialog1.FileName, FileMode.Open, FileAccess.ReadWrite),
    Encoding.UTF8
);

If you want to append, use FileMode.Append instead.

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.

UPDATE:

As per JinThakur's comment below, there is a constructor overload for StreamWriter that lets you do this directly:

var sw = new StreamWriter(saveFileDialog1.FileName, false, Encoding.UTF8);

The second parameter specifies whether the StreamWriter should append to the file if it exists, rather than truncating it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...