In my unit tests, I am using the following code to open a stream and write to it:
IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
stream = m_store.OpenFile(filename, FileMode.Create);
...
stream.Flush();
stream.Close();
stream.Dispose();
store.Dispose()
The first time it succeeds, but the second time it fails with the following log output:
Additional information: Operation not permitted on IsolatedStorageFileStream.
The FileMode.Create enum constant is defined as:
Specifies that the operating system should create a new file. If the file already exists, it will be overwritten. Create is equivalent to requesting that if the file does not exist, use CreateNew; otherwise, use Truncate.
so it appears this is the correct constant.
I have found a few similar questions on stackoverflow such as
IsolatedStorageFileStream exception is throw when file is opened?
but they didn’t help. As suggested somewhere on the net (can’t find the link now), I tried deleting the file first if it existed, contrary to the enum comments, like below, but didn’t help either:
if (store.FileExists(filename))
{
store.DeleteFile(filename);
}
QUESTION: What I am missing?
Thanks!
Firstly, you should really use a
usingstatement instead of explicitly callingCloseorDispose– otherwise if there’s an exception, you won’t have closed the stream.Secondly, I suspect the problem is that you haven’t disposed of the store itself. Try this: