如何在C#中使用StreamWriter多次编写和保存文件?

时间:2016-04-16 13:02:58

标签: c# file streamwriter

我试图打开一个文件,重写它,保存并在我的应用中多次关闭它,我发现了一个奇怪的行为

我打开文件:

System.IO.StreamReader file = new System.IO.StreamReader(filePath);

用这个写下来:

 using (System.IO.StreamWriter file = new System.IO.StreamWriter(filePath)) {
            file.WriteLine(myString);
            file.Close();
        }

但是在我关闭应用程序之前文件没有改变,为什么会发生这种情况?

我自己检查了文件,并且在应用关闭后内容并未发生变化

1 个答案:

答案 0 :(得分:0)

看起来您没有将更改刷新到磁盘。这可能是由于打开StreamReader句柄。每次写入后关闭阅读器并重新打开。或者在你写作之前更好地关闭阅读器并在之后重新打开它。