如果文件已经存在,该如何覆盖文件?

发布于 2025-01-23 08:36:59 字数 552 浏览 1 评论 0原文

我正在使用FastColoredTextbox制作文本编辑器。我有一个按钮,可让您将文本保存到PC上。问题在于,当用户试图将文件保存为已经存在的文件而不是覆盖文件时,它会引发异常。

这是我的代码。

SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt|*.txt|All files|*.*";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
    using (Stream s = File.Open(saveFileDialog1.FileName, FileMode.CreateNew))
    using (StreamWriter sw = new StreamWriter(s))
    {
        sw.Write(fastColoredTextBox1.Text);
    }
}

如果文件已经存在,我该如何使其覆盖该文件?

I'm making a text editor using fastColoredTextbox. I have a button that allows you to save your text onto your pc. The problem is that it throws an exception when the user tries to save the file as a file that already exists, instead of overwriting the file.

This is my code.

SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt|*.txt|All files|*.*";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
    using (Stream s = File.Open(saveFileDialog1.FileName, FileMode.CreateNew))
    using (StreamWriter sw = new StreamWriter(s))
    {
        sw.Write(fastColoredTextBox1.Text);
    }
}

How would I go about making it overwrite the file if it already exists?

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

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

发布评论

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

评论(2

半窗疏影 2025-01-30 08:36:59

我稍微更改了代码,最终将其处理过,以某种方式使它起作用。

SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt|*.txt|All files|*.*";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
    Stream s = saveFileDialog1.OpenFile();
    StreamWriter sw = new StreamWriter(s);
    sw.Write(fastColoredTextBox1.Text);
    sw.Close();
}

I changed up my code a bit and ended up going with this, which somehow got it to work.

SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt|*.txt|All files|*.*";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
    Stream s = saveFileDialog1.OpenFile();
    StreamWriter sw = new StreamWriter(s);
    sw.Write(fastColoredTextBox1.Text);
    sw.Close();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文