File.OpenWrite Is Evil

.NET Framework is full of the small helper methods and I personally find this beneficial in general. They make code easier to read and most of the time they also make errors less likely. They also lend themselves beautifully to the quick troubleshooting one-liners as a nice, temporary, and concise solution. There is almost no greater example for that flexibility than File helper methods.

If you need to read the content of the file, just say

using (var fileStream = File.OpenRead(filename)) {
    //do something
}

Similarly, if you need to write something, equivalent code is

using (var fileStream = File.OpenWrite(filename)) {
    //do something
}

However, there is a trap in the last code chunk as it doesn’t necessarily do what you might expect. Yes, file is opened for writing, but existing content is untouched. To illustrate the issue, save first John in the file and then Mellisa. File content will be, as expected, Mellisa. However, if you save John again, the content will be somewhat unexpected Johnisa.

Once seen as an example, it is obvious computer did exactly what we’ve told it. It opened the file for writing and modified the content starting from the first byte. Nowhere did we tell it to discard the old content.

Proper code for this case would be slightly longer:

using (var fileStream = new FileStream(fileName, **FileMode.Create**, FileAccess.Write)) {
    //do something
}

This will ensure file will be truncated before writing the new content and thus avoid the problem.

Annoying thing about this helper is that, under normal circumstances, it will work most of the time, biting you only when you delete/shorten something. I believe there is a case to argue it should have been designed with FileMode.Create instead of FileMode.Write as a more reasonable behavior. However, as it goes with most of these things, decision has already been made and there is no going back.