如果文件已经存在,该如何覆盖文件?
我正在使用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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
也许这可以帮助您:
https://learn.microsoft.com/es-es/es-es/dotnet/api/api/system.io.io.streamwriter.-ctor.-ctor?view=net-6.0 #System-io-streamwriter-ctor(System-string-System-boolean)
Maybe this could help you:
https://learn.microsoft.com/es-es/dotnet/api/system.io.streamwriter.-ctor?view=net-6.0#system-io-streamwriter-ctor(system-string-system-boolean)
我稍微更改了代码,最终将其处理过,以某种方式使它起作用。
I changed up my code a bit and ended up going with this, which somehow got it to work.