15

我有一个文件,其中包含我想监视更改以及添加我自己的更改的数据。像“Tail -f foo.txt”一样思考。

基于这个线程,看起来我应该只创建一个文件流,并将其同时传递给写入器和读取器。但是,当阅读器到达原始文件的末尾时,它看不到我自己编写的更新。

我知道这似乎是一个奇怪的情况......它更像是一个实验,看看它是否可以完成。

这是我尝试过的示例:


foo.txt:
a
b
c
d
e
f


        string test = "foo.txt";
        System.IO.FileStream fs = new System.IO.FileStream(test, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.ReadWrite);

        var sw = new System.IO.StreamWriter(fs);
        var sr = new System.IO.StreamReader(fs);

        var res = sr.ReadLine();
        res = sr.ReadLine();
        sw.WriteLine("g");
        sw.Flush();
        res = sr.ReadLine();
        res = sr.ReadLine();
        sw.WriteLine("h");
        sw.Flush();
        sw.WriteLine("i");
        sw.Flush();
        sw.WriteLine("j");
        sw.Flush();
        sw.WriteLine("k");
        sw.Flush();
        res = sr.ReadLine();
        res = sr.ReadLine();
        res = sr.ReadLine();
        res = sr.ReadLine();
        res = sr.ReadLine();
        res = sr.ReadLine();

超过“f”后,阅读器返回 null。

4

4 回答 4

24

好的,稍后进行两次编辑...

这应该有效。第一次尝试时,我想我忘记在 oStream 上设置 FileMode.Append。

string test = "foo.txt";

var oStream = new FileStream(test, FileMode.Append, FileAccess.Write, FileShare.Read); 
var iStream = new FileStream(test, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); 

var sw = new System.IO.StreamWriter(oStream);
var sr = new System.IO.StreamReader(iStream); 
var res = sr.ReadLine(); 
res = sr.ReadLine();
sw.WriteLine("g"); 
sw.Flush(); 
res = sr.ReadLine();
res = sr.ReadLine();
sw.WriteLine("h"); sw.Flush();
sw.WriteLine("i"); sw.Flush(); 
sw.WriteLine("j"); sw.Flush(); 
sw.WriteLine("k"); sw.Flush(); 
res = sr.ReadLine(); 
res = sr.ReadLine(); 
res = sr.ReadLine();
res = sr.ReadLine();
res = sr.ReadLine();
res = sr.ReadLine();
于 2010-09-28T22:37:45.897 回答
10

@mikerobi 是正确的,当您写入流时,文件指针会更改并移动到流的末尾。您不指望的是 StreamReader 有自己的缓冲区。它从文件中读取 1024 个字节,您将从该缓冲区中获得结果。直到缓冲区用完,所以它必须再次从 FileStream 中读取。什么也没找到,因为文件指针位于文件末尾。

您确实需要单独的 FileStreams,每个文件流都有自己的文件指针,以便有希望完成这项工作。

于 2010-09-28T23:10:54.397 回答
3

我相信每次你写一个字符时,你都在推进流位置,所以下一次读取尝试在你刚刚写的字符之后读取。发生这种情况是因为您的流阅读器和流编写器使用相同的 FileStream。使用不同的文件流,或在每次写入后在流中寻找 -1 个字符。

于 2010-09-28T22:35:19.130 回答
2

您不太可能对涉及使用相同流进行读取和写入的任何解决方案感到满意。如果您尝试使用StreamReader.

您希望有两个不同的文件流。StreamWriter如果你愿意,写作流可以是一个。读取流应该是二进制流(即用File.OpenReador创建FileStream.Create),从文件中读取原始字节,然后转换为文本。我对这个问题的回答显示了它是如何完成的基础知识。

于 2010-09-28T23:09:20.650 回答