Forcing StreamWriter to change Encoding

后端 未结 5 1225
没有蜡笔的小新
没有蜡笔的小新 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:27

    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.

提交回复
热议问题