Search code examples
c#silverlightwindows-phone-7windows-phone-8isolatedstorage

Operation not permitted on IsolatedStorageFileStream. error


I have a problem with isolated storage.

This is my code:

List<Notes> data = new List<Notes>();

using (IsolatedStorageFile isoStore = 
         IsolatedStorageFile.GetUserStoreForApplication())
{
  using (IsolatedStorageFileStream isoStream = 
           isoStore.OpenFile("Notes.xml", FileMode.OpenOrCreate))
  {
    XmlSerializer serializer = new XmlSerializer(typeof(List<Notes>));
    data = (List<Notes>)serializer.Deserialize(isoStream);              
  }
}

data.Add(new Notes() { Note = "hai", DT = "Friday" });

return data;

the mistake : Operation not permitted on IsolatedStorageFileStream. in

using (IsolatedStorageFileStream isoStream = 
        isoStore.OpenFile("Notes.xml", FileMode.OpenOrCreate))

Solution

  • This usually happens when you execute that code block several times concurrently. You end up locking the file. So, you have to make sure you include FileAccess and FileShare modes in your constructor like this:

    using (var isoStream = new IsolatedStorageFileStream("Notes.xml", FileMode.Open, FileAccess.Read, FileShare.Read, isolatedStorage)
    {
    //...
    }
    

    If you want to write to the file while others are reading, then you need to synchronize locking like this:

    private readonly object _readLock = new object();
    
    lock(_readLock)
    {
       using (var isoStream = new IsolatedStorageFileStream("Notes.xml", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None, isolatedStorage)
       {
            //...
       }
    }