读取和写入同一流中的文件 [英] Read and write to a file in the same stream

查看:42
本文介绍了读取和写入同一流中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以相同的方式读取和写入同一文件,以便其他程序无法在两者之间访问该文件:

I'm trying to read and write to the same file in a way such that no other program can access the file in between:

  FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);               
  StreamReader sr = new StreamReader(fs);
  StreamWriter sw = new StreamWriter(fs);
  newString = sr.ReadToEnd() + "somethingNew";
  sw.Write(newString);
  fs.Close();

文件永远不会被写入.如果我调试,则可以看到读取器设法获取文件的内容,但是写入器似乎无法写入该文件.什么都没发生.

The file is never written to. If I debug I can see that the reader manages to fetch the contents of the file, but the writer does not seem to be able to write to the file. Nothing happens.

我一直在查看此问题,似乎与我的问题相同.但是我无法使其正常工作.

I've been looking at this question which seems to be the same as mine. However I'm not able to get it to work.

推荐答案

只需

Just Flush your changes to file, Have sw.Flush(); before closing the stream. like:

string filePath = "test.txt";
FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
StreamReader sr = new StreamReader(fs);
StreamWriter sw = new StreamWriter(fs);
newString = sr.ReadToEnd() + "somethingNew";
sw.Write(newString);
sw.Flush(); //HERE
fs.Close();

您可能会看到此帖子同时用C#读写文件(打开多个流进行读写)

You may see this post simultaneous read-write a file in C# (open multiple streams for reading and writing)

这篇关于读取和写入同一流中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆