简体   繁体   English

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

[英]How do I overwrite a file if it already exists?

I'm making a text editor using fastColoredTextbox.我正在使用 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?如果文件已经存在,我将如何 go 覆盖它?

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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM