Search code examples
windows-phone-7windows-phone-7.1windows-phonewindows-phone-7.1.1

Operation not permitted on IsolatedStorageFileStream


I get an error when I open the file after it is created

using (var myFileStore = IsolatedStorageFile.GetUserStoreForApplication())
        {
            myFileStore.CreateFile(DateTime.Now.Ticks + ".txt");
        }
using (var myFileStore = IsolatedStorageFile.GetUserStoreForApplication())
        {
            temp = myFileStore.GetFileNames();
            for (int k = 0; k < temp.Length; k++)
            {
                IsolatedStorageFileStream file1 = myFileStore.OpenFile(temp[k], FileMode.Open, FileAccess.Read);
                dataSource.Add(new SampleData() { Name = temp[k], Size = Convert.ToString(Math.Round(Convert.ToDouble(file1.Length) / 1024 / 1024, 1) + " MB") });
            }
        }

Solution

  • That is due to the fact you didn't close the stream returned by the CreateFile method!

    Your code should look like this:

    using (var myFileStore = IsolatedStorageFile.GetUserStoreForApplication())
    {
        myFileStore.CreateFile(DateTime.Now.Ticks + ".txt").Dispose();
    }
    

    or

    using (var myFileStore = IsolatedStorageFile.GetUserStoreForApplication())
    {
        using(myFileStore.CreateFile(DateTime.Now.Ticks + ".txt"))
        {
        }
    }
    

    And the same in the OpenFile below.

    Bottom line you should always dispose your stream (by using the using clause or Dispose() method)