始终在isolatedstoragefilestream上不允许操作

时间:2014-03-22 12:37:52

标签: windows-phone-8

对此错误存在很多疑问,但我无法找到我面临的问题。

我有2个按钮:1个用于将一些字符串保存到isolatedStorage中,1个用于读取它。

当我尝试阅读它时,我得到了标题中写的errorMessage。

Button1.Click是:

using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            using (var stream = new IsolatedStorageFileStream("kedvencek" + ".txt",
                System.IO.FileMode.Append,
                System.IO.FileAccess.ReadWrite,
                store))
            {
                StreamWriter writer = new StreamWriter(stream);
                writer.WriteLine("something");
                writer.Close();
                stream.Close();
            }

和按钮2:

using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            using (var stream = new IsolatedStorageFileStream("kedvencek" + ".txt",
                System.IO.FileMode.Open,
                System.IO.FileAccess.ReadWrite,
                store))
            {
                StreamReader sr = new StreamReader(stream);
                string text = sr.ReadToEnd();
                MessageBox.Show(text);
                sr.Close();
                stream.Close();

            }

1 个答案:

答案 0 :(得分:0)

您面临的问题与as MSDN says:

这一事实有关
  

FileMode.Append只能与Write一起使用。

如果您将其更改为:

,它将起作用
using (var stream = new IsolatedStorageFileStream("kedvencek" + ".txt",
            FileMode.Append, FileAccess.Write, store))

另一方面,当你在stream离开using()之后,你不需要关闭using()。最好将StreamWriter放入using()

private void first_Click(object sender, RoutedEventArgs e)
{
    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
    using (var stream = new IsolatedStorageFileStream("kedvencek" + ".txt", FileMode.Append, FileAccess.Write, store))
    using (StreamWriter writer = new StreamWriter(stream))
    {
        writer.WriteLine("something");
    }
}

private void second_Click(object sender, RoutedEventArgs e)
{
    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
    using (var stream = new IsolatedStorageFileStream("kedvencek" + ".txt", FileMode.Open, FileAccess.ReadWrite, store))
    using (StreamReader sr = new StreamReader(stream))
    {
        string text = sr.ReadToEnd();
        MessageBox.Show(text);
    }
}