简体   繁体   English

IsolatedStorageFile不写入文件

[英]IsolatedStorageFile doesn't write to file

I have to store the contents of a control between sessions. 我必须在会话之间存储控件的内容。 This is what I do: 这是我的工作:

    private void Window_Closing(object sender, CancelEventArgs e)
    {
        IsolatedStorageFile f = IsolatedStorageFile.GetUserStoreForAssembly();
        using(IsolatedStorageFileStream stream = new IsolatedStorageFileStream("somefilename", FileMode.Create, f))
        using(StreamWriter writer = new StreamWriter(stream))
        {
            foreach(string path in searchFoldersListView.Items)
            {
                writer.WriteLine(path);
            }
        }
    }

This is attached to the Closing event of the window. 这附加到窗口的Closing事件。 When debugging, the control goes through all the items, but when I run the program again, the control is empty. 调试时,控件会遍历所有项目,但是当我再次运行程序时,控件为空。 It turns out that when I navigate to the file, it's empty. 事实证明,当我导航到该文件时,它是空的。 When I change the code to save to a regular file by putting a File.AppendAllText() in the foreach loop, that file is saved just fine. 当我通过将File.AppendAllText()放入foreach循环中来更改代码以将其保存到常规文件时,该文件的保存就很好。 Why is that? 这是为什么?

EDIT: reading event handler: 编辑:读取事件处理程序:

    private void Window_Initialized(object sender, EventArgs e)
    {
        IsolatedStorageFile f = IsolatedStorageFile.GetUserStoreForAssembly();
        using(IsolatedStorageFileStream stream = new IsolatedStorageFileStream("somefilename", FileMode.OpenOrCreate, f))
        using(StreamReader reader = new StreamReader(stream))
        {
            string line = reader.ReadLine();
            while(line != null)
            {
                searchFoldersListView.Items.Add(line);
            }
        }
    }

There is a bug in your method that reads from the file. 您的方法中存在一个从文件读取的错误。 You only read the first line which is probably null . 您只读取了可能为null的第一行。 Try the following: 请尝试以下操作:

    using(StreamReader reader = new StreamReader(stream))
    {
        string line = reader.ReadLine();
        while(line != null)
        {
            searchFoldersListView.Items.Add(line);
            line = reader.ReadLine();
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM