我有一个文件,其中包含我想监视的更改以及自己添加的更改的数据。像“ 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。
好的,稍后再进行两次编辑…
这应该工作。第一次尝试时,我想我忘记在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();