使用 File.CreateText 覆盖文件 (C#)
我遇到以下问题。我正在使用 .NET Framework 1.1,并且尝试使用以下代码覆盖文件:
try
{
using (StringWriter writer = new StringWriter())
{
Server.Execute(path, writer);
using (StreamWriter sr = File.CreateText(filepath + fileName))
{
sr.WriteLine(writer.ToString());
}
}
}
catch (Exception exc)
{
...
}
有时它工作正常,但有时它不会覆盖文件并且不会引发异常。有人可以告诉我问题可能是什么或者如何处理它不覆盖文件的原因吗?
I am experiencing the following problem. I am using .NET Framework 1.1 and I am trying to overwrite a file using this code:
try
{
using (StringWriter writer = new StringWriter())
{
Server.Execute(path, writer);
using (StreamWriter sr = File.CreateText(filepath + fileName))
{
sr.WriteLine(writer.ToString());
}
}
}
catch (Exception exc)
{
...
}
Sometimes it works fine, but sometimes it does not overwrite the file and no exception is thrown. Could someone tell me what the issue may be or how to handle why it doesn't overwrite the file?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为什么不只是:
来自 MSDN:
创建一个新文件,将指定的字符串写入该文件,然后关闭该文件。如果目标文件已存在,则将其覆盖。
Why not just:
From MSDN:
Creates a new file, writes the specified string to the file, and then closes the file. If the target file already exists, it is overwritten.
好吧,为了回答您的实际问题,
File.CreateText(string file)
的行为完全符合预期。如果使用您的示例,filepath + fileName
是一个已存在的文件,它将打开该文件而不是创建它。 (它不会覆盖)。您可以首先使用
File.Exists(string file)
然后使用File.Delete(string file)
检查文件是否存在。如果
File.CreateText(string file)
不满足您的需求,您可以尝试其他类型。也许FileInfo
?微软说:
来源:https:// /msdn.microsoft.com/en-us/library/system.io.file.createtext%28v=vs.110%29.aspx
Well, to answer your actual question,
File.CreateText(string file)
is behaving exactly as intended. iffilepath + fileName
to use your example, is a file that already exists, it opens the file instead of creating it. (It does not overwrite).You could first check to see if the file exists using
File.Exists(string file)
thenFile.Delete(string file)
.If
File.CreateText(string file)
doesn't suit your needs, you could try a different type. MaybeFileInfo
?Microsoft Says:
Source: https://msdn.microsoft.com/en-us/library/system.io.file.createtext%28v=vs.110%29.aspx
覆盖写入也可以通过内置的 file.copy 方法来实现。
File.copy 过载 -
msdn 上的更多信息
希望这会有所帮助。
over write can also be achieved with built in file.copy method.
File.copy has overload -
more info on msdn
hope this helps.