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

时间:2012-06-07 19:40:53

标签: c# visual-studio windows-phone-7

我在第二个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

1 个答案:

答案 0 :(得分:1)

你第二次重用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