68

I was using the following to write to a file:

using(Stream FileStream = File.OpenWrite(FileName)) 
   FileStream.Write(Contents, 0, Contents.Length);

I noticed that it was simply writing to file file correctly, but didn't wipe the contents of the file first. I then decided to simply use:

File.WriteAllBytes(FileName, Contents);

This worked fine.

However, why doesn't File.OpenWrite automatically delete the contents of the file as the other languages i've used do for their OpenWrite style function, and have a instead of appending?

Is there any method to do this?

1

2 Answers 2

110

This is the specified behavior for File.OpenWrite:

If the file exists, it is opened for writing at the beginning. The existing file is not truncated.

To do what you're after, just do:

using(Stream fileStream = File.Open(FileName, FileMode.Create)) 
   fileStream.Write(Contents, 0, Contents.Length);

Your current call is equivalent to use FileMode.OpenOrCreate, which does not cause truncation of an existing file.

The FileMode.Create option will cause the File method to create a new file if it does not exist, or use FileMode.Truncate if it does, giving you the desired behavior. Alternatively, you can use File.Create to do this directly.

2
  • 3
    I just thought it was a bit of an unneeded discrepancy from most IO libraries I've used which usually have writing as overwriting then have a different method for appending. Thanks for the info on how to actually open and clear, much appreciated.
    – Blam
    Sep 6, 2010 at 17:13
  • @Blam: No problem. In .NET, Open, Create, and Truncate all have unique meanings (which is why I tried to answer it showing the FileModes, since that's really the only place that lists them all clearly). Glad it helps :) Sep 6, 2010 at 17:26
32

Yes you are right. File.OpenWrite does not overwrite the file.

The File.Create is used to overwrite the file if exists.

1
  • This is the correct answer. Though to extend it with an example... File.Open(<filename>, FileMode.Create, FileAccess.Write) Optionally, you may use the 4th argument to determine what kind of exclusive lock, if any, you want on the file. By default, you won't even be able to open the file to read in another program. E.g. File.Open(<filename>, FileMode.Create, FileAccess.Write, FileShare.ReadWrite)
    – TomWardrop
    May 22, 2017 at 6:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.