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

编程入门 行业动态 更新时间:2024-10-25 12:24:27
本文介绍了读取和写入同一流中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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)

更多推荐

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

本文发布于:2023-11-06 22:34:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1564856.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   一流中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!