0

每当我运行此代码时:

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

1 回答 1

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

实际上 using 的作用是 using 将调用 dispose 方法,使其可重用。storage、file stream、streamwriter 有 dispose 方法,这些方法实际上有利于使用“使用”。这通常不会引发维护资源的异常,但关于文件名的参数异常仍然会引起问题。

在处理文件和输入时,必须始终使用 Try...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();
        }
   }
}
于 2013-09-21T18:28:42.810 回答