我正在尝试以相同的方式读取和写入同一文件,以便其他程序无法在两者之间访问该文件:
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.
推荐答案只需 Flush 您对文件所做的更改,请先关闭 sw.Flush(); ,然后再关闭流.像:
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)
更多推荐
读取和写入同一流中的文件
发布评论