使用IsolatedStorageFileStream时出现问题

时间:2013-09-21 17:43:15

标签: c# windows-phone-7

每当我运行此代码时:

IsolatedStorageFile fileStorage = IsolatedStorageFile.GetUserStoreForApplication();
StreamWriter Writer = new StreamWriter(new IsolatedStorageFileStream("TestFile.txt", FileMode.OpenOrCreate, fileStorage));
Writer.WriteLine(email1.Text + "," + email2.Text + "," + email3.Text + "," + email4.Text);
Writer.Close();

我收到此错误:

An exception of type 'System.IO.IsolatedStorage.IsolatedStorageException' occurred in mscorlib.ni.dll but was not handled in user code

我正在使用模拟器,但这应该不是问题。我已经包含了这行

Using System.IO.IsolatedStorage;

1 个答案:

答案 0 :(得分:3)

使用IsolatedStorage时遇到的问题是

  

System.IO.IsolatedStorage.IsolatedStorageException

这是因为您在使用它之后实际上并没有关闭存储。这也会引发安全性方面的异常。将代码重写为:

using (var storage = IsolatedStorageFile.GetUserStoreForApplication())
        {
            using (var file = storage.OpenFile("TestFile.txt", System.IO.FileMode.OpenOrCreate))
            {
                using (System.IO.StreamWriter writer = new System.IO.StreamWriter())
                {
                    writer.WriteLine(email1.Text + "," + email2.Text + "," + email3.Text + "," + email4.Text);
                }
            }
        }

实际使用的是使用将调用dispose方法使其可重用。存储,文件流,流写器已经配置了使用“使用”实际上有益的方法。这通常不会引发维护资源的异常,但是有关文件名的参数异常仍然存在问题。

  

尝试...在处理文件和输入时必须始终使用catch。

修改 代码如何阅读:

string dataToRead = string.Empty;
using (var storage = IsolatedStorageFile.GetUserStoreForApplication())
{
   using (var file = storage.OpenFile("TestFile.txt", System.IO.FileMode.Open))
   {
        using (var reader = new System.IO.StreamReader(file))
        {
                dataToRead = reader.ReadToEnd();
        }
   }
}