且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

读取和写入同一流中的文件

更新时间:2022-11-08 11:11:27

只需

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)