Forcing StreamWriter to change Encoding

你离开我真会死。 提交于 2019-11-28 20:16:34

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.

There is a constructor for filename, appendMode, encoding.

With a proper using block it looks like:

if (dr == DialogResult.OK)
{
    using (StreamWriter sw = new StreamWriter(saveFileDialog1.FileName, 
           false, Encoding.UTF8))
    {
      sw.Write(sb.ToString());
      //sw.Close();
    }
}

There is a StreamWriter(string path, bool append, Encoding encoding) constructor - you could just explicitly specify the append flag too?

I said you ought to wrap your StreamWriter in a using too, i.e.

if (dr == DialogResult.OK)
{
    using(StreamWriter sw = new StreamWriter(saveFileDialog1.FileName, false, Encoding.UTF8)) {
        sw.Write(sb.ToString());
        sw.Close();
    }
}

although realistically this won't make any difference here. This effectively puts a try/finally around the code so that the StreamWriter will get cleaned up (it'll call sw.Dispose() even if an exception gets thrown in the meantime. (Some people will say this also means you no longer need the .Close since the Dispose will take care of that too but I prefer to have it anyway.)

setting UTF8 encoding working with Arabic font is the best thing I did:

 using (var sw = new StreamWriter(

 new FileStream(temporaryFilePath,    
               FileMode.Create,
               FileAccess.ReadWrite), 
               Encoding.UTF8))
            {
                sw.Write(sb.ToString());
            }
 )
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!