强制 StreamWriter 更改编码

发布于 2024-12-15 14:08:43 字数 572 浏览 3 评论 0原文

我正在尝试使用 DialogResultStringBuilder 保存文件。制作文本后,我调用以下代码来保存文件:

    if (dr == DialogResult.OK)
    {

        StreamWriter sw = new StreamWriter(saveFileDialog1.FileName);

        sw.Write(sb.ToString());
        sw.Close();
    }

我尝试将第二个参数添加到 StreamWriter 作为 Encoding.UTF8 但由于第一个参数是string 而不是 Stream,它不会编译它。

如何将该字符串转换为流以便能够将第二个参数作为编码传递?

这样做的原因是,在我的文本中的某处我有 μ 但当文件保存时它显示为 Î⁄ 所以 μ 正在变得搞砸了!

谢谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

难理解 2024-12-22 14:08:43

只需将其包装在 FileStream 中即可。

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

如果您想追加,请改用FileMode.Append

您还应该在 try/finally 块上调用 Dispose(),或者使用 using 块在对象超过 >using 范围:

using(
    var sw = new StreamWriter(
        new FileStream(saveFileDialog1.FileName, FileMode.Open, FileAccess.ReadWrite),
        Encoding.UTF8
    )
)
{
    sw.Write(sb.ToString());
}

这将正确关闭并处理所有异常路径上的流。

更新:

根据下面 JinThakur 的评论,有 StreamWriter 的构造函数重载,可让您直接执行此操作:

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

第二个参数指定StreamWriter 是否应附加到文件(如果存在),而不是截断它。

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.

李白 2024-12-22 14:08:43

有一个文件名、appendMode、编码的构造函数。

使用正确的 using 块,它看起来像:

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

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();
    }
}
烟燃烟灭 2024-12-22 14:08:43

有一个 StreamWriter(string path, bool append, Encoding 编码) 构造函数- 您也可以明确指定附加标志吗?

我说你应该将 StreamWriter 包装在 使用< /a> 也是如此,

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

即尽管实际上这在这里不会有任何区别。这有效地在代码周围放置了一个 try/finally ,以便 StreamWriter 得到清理(即使同时抛出异常,它也会调用 sw.Dispose() 。(有些人会说这也意味着您不再需要 .Close 因为 Dispose 也会处理这个问题,但无论如何我更喜欢拥有它。)

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

半边脸i 2024-12-22 14:08:43

设置 UTF8 编码与阿拉伯字体一起使用是我做的最好的事情:

 using (var sw = new StreamWriter(

 new FileStream(temporaryFilePath,    
               FileMode.Create,
               FileAccess.ReadWrite), 
               Encoding.UTF8))
            {
                sw.Write(sb.ToString());
            }
 )

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());
            }
 )
傲影 2024-12-22 14:08:43

最简单的方法是使用正确的构造函数。

StreamWriter(String, Boolean, Encoding)

使用指定的编码和默认缓冲区大小初始化指定文件的 StreamWriter 类的新实例。如果该文件存在,则可以覆盖或附加该文件。如果该文件不存在,则此构造函数将创建一个新文件。

C#

public StreamWriter (string path, bool append, System.Text.Encoding encoding);

The easiest way is to use the right constructor.

StreamWriter(String, Boolean, Encoding)

Initializes a new instance of the StreamWriter class for the specified file by using the specified encoding and default buffer size. If the file exists, it can be either overwritten or appended to. If the file does not exist, this constructor creates a new file.

C#

public StreamWriter (string path, bool append, System.Text.Encoding encoding);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文