overwriting file with File.CreateText (C#)
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())
开发者_如何学C{
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?
Why not just:
File.WriteAllText(Path.Combine(filepath, fileName), writer.ToString())
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.
Could someone tell me what the issue may be or how to handle why it doesn't overwrite the file?
Well, to answer your actual question, File.CreateText(string file)
is behaving exactly as intended. if filepath + 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)
then File.Delete(string file)
.
If File.CreateText(string file)
doesn't suit your needs, you could try a different type. Maybe FileInfo
?
Microsoft Says:
Creates or opens a file for writing UTF-8 encoded text.
Source: https://msdn.microsoft.com/en-us/library/system.io.file.createtext%28v=vs.110%29.aspx
over write can also be achieved with built in file.copy method.
File.copy has overload -
File.Copy Method (Source, Destination, OverWrite)
more info on msdn
hope this helps.
精彩评论