Click here to Skip to main content
15,896,336 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Is it possible to write over an existing file in Server.MapPath(file.xml) using:
C#
using (FileStream fsAppend = new FileStream(Server.MapPath("file1.xml"), FileMode.Append, FileAccess.Write))
{
   StreamWriter sw = new StreamWriter(fsAppend);
   ???
}

Or somehow using FileMode.Truncate?? then FileMode.Create?

What I have tried:

FileMode.Append seems the way to go if I figure out the Syntax. I do not want to even try FileMode.Truncate at all.
Posted
Updated 1-Apr-17 23:26pm

1 solution

FileMode.Append always opens the file and if it exists, sets the write position to the end of the stream. So it will never replace the existing file, it just adds to it.
FileMode.Create is the one you want: it replaces an existing file if one exists, or creates a new file if it doesn't.

But ... and it's a big "but ... be careful to use a try...catch block with your code: websites are intrinsically multiuser, and standard FileIO operations which involve writing always lock the file for exclusive access. If the file is in use by another website user, your code will fail.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900