简体   繁体   English

为什么我的StreamWriter没有写入.txt文件?

[英]Why is my StreamWriter not writing to a .txt file?

I am try to write a file but it is still empty ... 我试着一个文件,但它仍然是空的 ......

 FileStream f = new FileStream("HighScore.txt", 
                                FileMode.OpenOrCreate, 
                                FileAccess.ReadWrite);

 StreamWriter streamWriter = new StreamWriter(f);
 streamWriter.WriteLine("aaaaa");

Has anyone encountered this problem and can help me? 有没有人遇到这个问题,可以帮助我吗?

You have to Close the writer; 你必须Close作家; since StreamWriter is IDisposable let's do it with a using : 因为StreamWriterIDisposable我们可以using

 using(FileStream f = new FileStream("HighScore.txt", 
                                      FileMode.OpenOrCreate, 
                                      FileAccess.ReadWrite)) {
   using(StreamWriter streamWriter = new StreamWriter(f)) {
     streamWriter.WriteLine("aaaaa");
   }
 }

Usually, writers cache the updates and apply them on closing. 通常,编写器会缓存更新并在关闭时应用它们。 If you want to apply changes somewhere the middle of the process , call Flush() . 如果要在过程中间的某处应用更改,请调用Flush() In case you want just to write text to the file you can put it easier 如果您只想将文本写入文件,可以更容易

File.WriteAllText("HighScore.txt", "aaaaa");

StreamWriter is buffering your data. StreamWriter正在缓冲您的数据。 The buffered data is automatically flushed when full or when closing the connection, you're not doing any of it. 缓冲数据在满时自动刷新或关闭连接时,您没有执行任何操作。

Your situation is the data is too small, and thus not flushed. 你的情况是数据太小,因此没有刷新。

Closing the connection will solve the problem. 关闭连接将解决问题。

You have few options. 你有几个选择。

Manual Flush - Less recommended 手动冲洗 - 少推荐

Manually add flush when you want to save the data. 要保存数据时手动添加刷新。

steamWriter.Flush()

Closing the connection manually - better, but still not best. 手动关闭连接 - 更好,但仍然不是最好的。

streamWriter.Close();

Disposing the connection - best. 处理连接 - 最好。

Wrapping the code with using will dispose the resource when the scope {..} is finished, the dispose operation will close the connection and thus flush your data. 包装的代码与using将部署在范围内的资源{..}完成后,脱手操作将关闭连接,从而刷新您的数据。

using (var f = new FileStream("HighScore.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite))
using (var streamWriter = new StreamWriter(f))
{
    streamWriter.WriteLine("aaaaa");
}

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

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