Reputation: 35901
I am developing a simple ASP.NET WebApi application. In a controller I have a POST action that does the following code:
using (var isoStore = IsolatedStorageFile.GetUserStoreForAssembly())
{
using (var textWriter = new StreamWriter(
isoStore.OpenFile(filename, FileMode.OpenOrCreate | FileMode.Truncate)))
{
// write to file
}
}
which throws the FileNotFoundException
exception on the using
line when the file does not exist (it works fine when the file exists).
When I rewrite it as follows:
using (var isoStore = IsolatedStorageFile.GetUserStoreForAssembly())
{
StreamWriter textWriter;
if (!isoStore.FileExists(filename))
{
textWriter = new StreamWriter(isoStore.CreateFile(filename));
}
else
{
textWriter = new StreamWriter(
isoStore.OpenFile(filename, FileMode.Open | FileMode.Truncate));
}
}
everything works fine, and I can write to the file, regardless whether it existed or not.
Isn't the purpose of OpenOrCreate
to cover both cases from the second snippet in a single call?
Upvotes: 4
Views: 663
Reputation: 5402
FileMode
enum is not a flag type enum, which means you should not perform bitwise operations on it. FileMode.OpenOrCreate | FileMode.Truncate
resolves to FileMode.Truncate
which expects a file to be there.
In general OpenOrCreate
and Truncate
are two different modes of opening a file, so you need to chose one (Create
being a reasonable alternative for what you need, credit to @Damien_The_Unbeliever).
Upvotes: 7