隔离存储 - 延迟和错误工作

时间:2013-04-02 11:13:43

标签: windows-phone-7

我在WP7中编写了我的第一个应用程序,我对IS有一个奇怪的问题:

                case "pn_s":            
                IsolatedStorageFile isoStorage = IsolatedStorageFile.GetUserStoreForApplication();
                //IsolatedStorageFileStream isoStream = isoStorage.CreateFile("plan_zajec_pn.txt"); 
                IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(("plan_zajec_pn.txt"), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None, isoStorage);
                StreamWriter writer = new StreamWriter(isoStream);
                string dane="";
                for (int i = 0; i < 10; i++)
                {
                    dane += godzina[i].Text;
                    dane += ";";
                    dane += przedmiot[i].Text;
                    dane += ";";
                    dane += sala[i].Text;
                    dane += ";";
                }
                writer.WriteLine(dane);
                isoStream.Close();
                break;

实际上它不起作用...... 我重新打开应用程序后创建文件,但它是空的,我已经检查了&#34; dane&#34;它包含日期

1 个答案:

答案 0 :(得分:0)

使用StreamWriter时,不得关闭基础流,否则编写器可能没有足够的时间写入所有数据。只需关闭作者,它就会关闭流。此外,即使发生错误,您也应该将您的流封装在using语句中以关闭它们。

最后,您的代码应如下所示:

case "pn_s":            
    using (var isoStorage = IsolatedStorageFile.GetUserStoreForApplication())
    {
        using (var isoStream = new IsolatedStorageFileStream(("plan_zajec_pn.txt"), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None, isoStorage))
        {
            using (var writer = new StreamWriter(isoStream))
            {
                string dane = "";

                for (int i = 0; i < 10; i++)
                {
                    dane += godzina[i].Text;
                    dane += ";";
                    dane += przedmiot[i].Text;
                    dane += ";";
                    dane += sala[i].Text;
                    dane += ";";
                }

                writer.WriteLine(dane);
            }
        }
    }

    break;