Forcing StreamWriter to change Encoding

后端 未结 5 1226
没有蜡笔的小新
没有蜡笔的小新 2020-12-14 06:58

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:



        
5条回答
  •  臣服心动
    2020-12-14 07:21

    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.)

提交回复
热议问题