DeleteFile在上下文菜单中抛出IsolatedStorageFileException

本文关键字:IsolatedStorageFileException 菜单 上下文 DeleteFile | 更新日期: 2023-09-27 18:06:41

用Silverlight为Windows Phone (XAML/c#)编写WP7.1 (Mango)应用程序。我有一个无法摆脱的例外。我有一个ListBox,显示ObservableCollection<string>,其中显示IsolatedStorage的XML文件的文件名。Listbox控件还包含来自Windows Phone Toolkit的ContextMenu。我用它从我的ListBox和磁盘中删除项目。

ContextMenu和我的删除方法工作正常…但是,如果在没有导航的同一页面上,我创建一个新文件(让我们称之为File1),然后创建另一个文件(File2),如果我然后尝试删除File1, IsolateStorageFile.DeleteFile方法抛出一个异常,说明"访问IsolatedStorage时发生错误",内部消息为null。然而,如果我创建File1,那么File2。然后删除File2,然后File1,它工作得很好!啊!

如果我离开页面或重新启动应用程序,我可以删除文件,没有问题。

我已经简化了代码,希望能让它更容易阅读。

UI绑定集合字段。

    ObservableCollection<string> Subjects;

点击事件调用写方法。

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

将文件添加到IsoStore和Subjects集合的方法。返回一个bool值,用于条件UI操作。

    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;
    }

ContextMenu点击事件调用删除文件方法

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

和我的delete方法

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

代码是直接的,我只是不知道我错过了什么。(

DeleteFile在上下文菜单中抛出IsolatedStorageFileException

OpenFile得到IsolatedStorageFileStream。您需要在另一个操作可以操作它之前将其处理掉。

顺便说一句,using语句为您调用dispose,因此不需要在using语句的末尾调用dispose。