2010-09-28 207 views
13

我有一个文件,其中包含希望监视更改的数据以及添加自己的更改。想像“尾巴-f foo.txt”。同时读写C#中的文件

基于this thread,看起来我应该创建一个文件流,并将它传递给作者和读者。但是,当读者到达原始文件的末尾时,它无法看到我自己写的更新。

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

下面是示例情况下,我尝试:


foo.txt的:
一个
b
Ç
d
Ë
˚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。

+0

一张海报确实提出了有关将两个文件流指向同一个对象的事情......这确实有效。即使读者到达文件末尾,如果作者更新,读者流也会得到两个结果。 – tbischel 2010-09-28 22:57:59

+0

是的,那是我删除我的帖子后,它没有像我预期的那样工作。我解除了它的解释,为什么... – MarkPflug 2010-09-28 23:04:06

回答

20

好,二编辑后...

这应该工作。第一次尝试时,我想我忘记了在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(); 
+0

我chnaged OStream的FileShare.ReadWrite。 – Mehmet 2016-12-28 09:03:56

1

如果您添加对StreamReader.DiscardBufferedData()的呼叫,是否会改变行为?

+0

这使得流读取为空,只要我叫它。 – tbischel 2010-09-28 22:37:17

3

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

+0

以及我交错写和读的方式是看看是否是这种情况。阅读器依然按顺序正确读取,但它看不到作者添加的任何新数据。 – tbischel 2010-09-28 22:38:33

2

这是极不可能的,你会很乐意与任何解决这个问题涉及使用用于读取和写入相同的流。如果您试图使用StreamReader来读取文件尾部,则尤其如此。

你想有两个不同的文件流。如果你喜欢,写作流可以是StreamWriter。阅读流应该是一个二进制流(即用File.OpenReadFileStream.Create创建),从该文件读取原始字节并转换为文本。我对this question的回答显示了它如何完成的基础知识。

9

@mikerobi是正确的,当你写入流时文件指针被改变并移动到流的末尾。你不在指望的是StreamReader有它自己的缓冲区。它从该文件读取1024个字节,您将从该缓冲区获得结果。直到缓冲区用完,所以它必须再次从FileStream读取。由于文件指针位于文件的末尾,因此没有发现任何内容。

你确实需要分开FileStreams,每个FileStreams都有自己的文件指针,以便有任何希望使其工作。

+0

感谢Hans,我一直在努力确认这一事实,试图自己开发解决方案。看到我似乎得出同样的结论是有帮助的。 – jpierson 2012-04-07 03:13:12