2013-06-19 131 views
-5

按解决方案张贴在下面的文章中,我已经创建了形式写入日志条目时,但是我得到file in use例外读取日志文件如何读取日志从日志文件,因为它发生

BackgroundWorker & Timer, reading only new lines of a log file?

帮助

+0

_“help”_ - 是你的问题吗?你是否可以证明你明白了这个问题,你知道_something_关于如何打开,锁定,读写文件的工作原理,你是否已经将问题指向了一个可重复的测试用例,或者你只是想修复该死的代码? – CodeCaster

+0

你是指“阅读”日志条目吗? – DonBoitnott

+0

@Nitin你需要正确处理streamReader或fileStream。 – Praveen

回答

1

当我做这样的文件访问/操纵我通常照顾两件事情。

首先,阅读中,我使用下面的代码(见FileShare enumeration):

using (Stream s = File.Open(path, FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite)) { ... } 

其次,我平时写一个while循环,打开文件进行读/写这样的(代码草案):

int tries=0; 
while (tries < 10) { 
    try { 
     // try to open file for your operation 
     break; 
    } catch (IOException) { 
     tries++; 
     Thread.Sleep(200); 
    } 
} 

编辑:意外地,我用第一次在我的答案FileShare.Read而不是更合适的FileShare.ReadWrite。现在我已经纠正它。

+0

实际上可以将文件同时写入和读取。如[tail](http://en.wikipedia.org/wiki/Tail_(Unix))所示,用于查看正在写入日志的日志,这似乎是OP试图复制的内容。 – Clafou

+0

我只是想给出一些一般的想法。 –