WP7设备中IsolatedStorage的奇怪问题

时间:2013-04-19 21:29:38

标签: c# windows-phone-7 xml-serialization isolatedstorage onedrive

我的Windows Phone 7应用程序中存在一个奇怪的问题。我需要在我的应用中读/写某些xml文件,我正在使用IsolatedStorage来收集数据。我的应用程序从SkyDrive发送/获取数据,这就是我使用它的原因。

好的,这是生成异常的函数:

private void CreateFileIntoIsolatedStorage(List<Record> list)
    {
        isf = IsolatedStorageFile.GetUserStoreForApplication();
        if(list.Count == 0)
            list = new List<Record>() { new Record { Date = DateTime.Today, Value = 0 }};

        if (isf.FileExists(fileName))
        {
            isf.DeleteFile(fileName);
        }

        XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();
        xmlWriterSettings.Indent = true;

        using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
        {
            using (IsolatedStorageFileStream stream = myIsolatedStorage.OpenFile(fileName, FileMode.Create))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(List<Record>));
                using (XmlWriter xmlWriter = XmlWriter.Create(stream, xmlWriterSettings))
                {
                    serializer.Serialize(xmlWriter, list);
                }
            }
        }
    }

问题:

我的问题在我第二次运行此功能时启动。然后isf.DeleteFile(fileName);抛出IsolatedStorageException。并创建stream崩溃的应用程序。

这很奇怪,因为每当我在设备上运行它时都会发生这种情况,很少在我使用调试器时发生。

所以我的问题是我如何解决它还是有更好的方法来做到这一点?

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:2)

可能是因为在你的方法开始时你有:

isf = IsolatedStorageFile.GetUserStoreForApplication();

你永远不会处理它。然后,稍后,您将在using中再次获取它。但是那个人被处置了。然后,当你下次打电话给CreateFileIntoIsolatedStorage时,你再次得到它,再次没有处理。

也许这就是你想要的:

using (var isf = IsolatedStorageFile.GetUserStoreForApplication())
{
    if(list.Count == 0)
        list = new List<Record>() { new Record { Date = DateTime.Today, Value = 0 }};

    if (isf.FileExists(fileName))
    {
        isf.DeleteFile(fileName);
    }
}

虽然这个类范围的isf变量很麻烦。如果您想让商店保持活跃状态​​,那么只需将其调用一次并保持打开即可。否则,抛弃类范围的变量。

或者,可能是由于此原因,来自IsolatedStorageFile.DeleteFile的文档?

  

文件缺失受到间歇性故障,因为文件可以由操作系统的功能,如病毒扫描程序和文件索引是在同时使用。对于最近创建的文件尤其如此。 Macintosh用户应该知道这个问题,因为它经常索引。   由于这些原因,重要的是添加代码以处理该IsolatedStorageException重试删除文件或日志失败的代码块是重要的。

我会建议像:

int retryCount = 0;
while (retryCount < MaxRetryCount && isf.FileExists(fileName))
{
    try
    {
        isf.DeleteFile(fileName);
    }
    catch (IsolatedStorageException)
    {
        ++retryCount;
        // maybe notify user and delay briefly
        // or forget about the retry and log an error. Let user try it again.
    }
}