独立存储的行为很奇怪,可以保存一个文件,但不能保存第二个文件

本文关键字:保存 文件 一个 第二个 但不能 存储 独立 | 更新日期: 2023-09-27 18:36:27

我在第二个using(StreamWriter语句中得到以下内容:

值不在预期范围内。

            #region save allowance
            IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
            //Open existing file
            IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile("foo.txt", FileMode.Truncate, FileAccess.Write);
            using (StreamWriter writer = new StreamWriter(fileStream))
            {
                writer.Write(App.ViewModel.Foo);
            }
            #endregion
            #region save log
            IsolatedStorageFileStream fileStream2 = myIsolatedStorage.OpenFile("log.txt", FileMode.Truncate, FileAccess.Write);
            using (StreamWriter writer = new StreamWriter(fileStream))
            {
                foreach( var i in App.ViewModel.Items )
                    writer.Write(i.ToString());
            }
            #endregion

独立存储的行为很奇怪,可以保存一个文件,但不能保存第二个文件

您第二次重用 fileStream 而不是 fileStream2。顺便说一下,为了避免这种错误,您可能希望将文件流包装在 using 块中。

        #region save allowance
        IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
        //Open existing file
        using (var writer = new StreamWriter(myIsolatedStorage.OpenFile("foo.txt", FileMode.Truncate, FileAccess.Write)))
        {
            writer.Write(App.ViewModel.Foo);
        }
        #endregion
        #region save log
        using (var writer = new StreamWriter(myIsolatedStorage.OpenFile("log.txt", FileMode.Truncate, FileAccess.Write)))
        {
            foreach( var i in App.ViewModel.Items )
                writer.Write(i.ToString());
        }
        #endregion