0

I have a strange problem in my Windows Phone 7 application. I need to read/write some xml file in my app and I'm using IsolatedStorage to collect data. My app sends/gets data from SkyDrive this is why I use it.

Ok, here is function which generate exception:

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

Problem:

My problem starts when I this function runs for the second time. Then isf.DeleteFile(fileName); throws IsolatedStorageException. And creating stream crashed application.

It's strange cause it happens every time I run it on my device, and rarely when I use the debugger.

So my question is how can I solve it or are there better ways to do this?

Any help would be appreciated.

4

1 回答 1

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.
    }
}
于 2013-04-19T23:56:08.807 回答