编写文件时“IsolatedStorageFileStream上不允许操作”

时间:2013-07-12 13:57:47

标签: c# serialization windows-phone-8 isolatedstorage

我正在尝试使用二进制序列化和从WPPerfLab获取的一些帮助程序序列化一个对象,我在这一行中得到了错误:

using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(FileName, FileMode.Create, myIsolatedStorage))

这是我正在做的事情的简短片段。

    using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
        {
            if (myIsolatedStorage.FileExists(FileName))
            {
                myIsolatedStorage.DeleteFile(FileName);
            }                
            using (IsolatedStorageFileStream fileStream = new IsolatedStorageFileStream(FileName, FileMode.Create, myIsolatedStorage))
            {                                        
                new BinarySerializationHelper().Serialize(fileStream, object);
            }
    }

经过一些谷歌搜索后,我发现这可能是一个与流相关的错误,但我很确定没有其他流可以打开我正在尝试写入的文件(名称也是随机的!)。

那么,我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

我找到了你的错误兄弟。实际上,错误的原因不是IsolatedStorageFileStream,而是无辜的字符串FileName。

我想你正在生成FIleName为

string FileName =" some_random_string" + DateTime.Now.ToString(" hh:mm");

或您正在使用的日期时间格式。在这一行上设一个断点。您会发现FileName值包含一个字符':' ....非常非常糟糕的命名。因此错误。尝试以其他方式命名文件。

但是这个IsolatedStorageFileStream构造函数让我很烦恼。所以我用另一种方式。我正在使用IsolateStorage流的方法来打开文件。看一下代码

 using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
    {
        if (myIsolatedStorage.FileExists(FileName))
        {
            myIsolatedStorage.DeleteFile(FileName);
        }                
        using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(FileName, System.IO.FileMode.CreateNew))
        {                                        
            new BinarySerializationHelper().Serialize(fileStream, object);
        }
}
相关问题