Question

Writing a WP7.1 (Mango) app in Silverlight for Windows Phone (XAML / C#). I have an exception that I just cannot shake. I have a ListBox displaying an ObservableCollection<string> which displays the file names of XML files from IsolatedStorage. The Listbox control also contains a ContextMenu from the Windows Phone Toolkit. I use it to delete items from my ListBox, and from disk.

The ContextMenu and my delete method works fine normally... But if, whilst on the same page without navigating away, I create a new file (let's call it File1) then create another file (File2), if I then attempt to delete File1, the IsolateStorageFile.DeleteFile method throws an exception stating "An error occurred while accessing IsolatedStorage" with an inner message of null. HOWEVER, if I create File1, then File2. Then delete File2 then File1, it works just fine! ARGH!

If I leave the Page or restart the app again, I can delete the file no problems.

I've stripped back the code to hopefully make it a bit easier to read.

UI Binding Collection field in the code behind.

    ObservableCollection<string> Subjects;

Click event calls the write method.

    private void Button_Click_AddNewSubject(object sender, RoutedEventArgs e)
    {
        if (TryWriteNewSubject(NewSubjectNameTextBox.Text))
        {
            ... Manipulate UI
        }
    }

Method to Add file to IsoStore and Subjects collection. Returns a bool for conditional UI manipulation.

    private bool TryWriteNewSubject(string subjectName)
    {
            ... file name error checking 

                using (var store = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    store.OpenFile(subjectName + ".xml", FileMode.CreateNew);
                    store.Dispose();
                }
                Subjects.Add(subjectName);
                return true;
            }
            else return false;
        }
        else return false;
    }

The ContextMenu click event calls the delete file method

    private void ContextMenuButton_Click(object sender, RoutedEventArgs e)
    {
        string subjectName = (sender as MenuItem).DataContext as string;
        DeleteFile(subjectName);
    }

And my delete method

    private void DeleteFile(string subjectName)
    {
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                string fileName = subjectName + ".xml";
                store.DeleteFile(fileName);
                Subjects.Remove(subjectName);
            }
    }

The code is straight forward, I just don't know what I'm missing. :(

Was it helpful?

Solution

You get a IsolatedStorageFileStream from OpenFile. You need to dispose it before another operation can manipulate it.

Btw, a using statement calls dispose for you, so there's no need to call dispose at the end of a using statement.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top