即使“正在被另一个进程使用",我如何读取文件?例外? [英] How can I read a file even when getting an "in use by another process" exception?

查看:36
本文介绍了即使“正在被另一个进程使用",我如何读取文件?例外?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 VB.NET 或 C# 中,我试图读取另一个程序正在使用的文本文件的内容(这就是重点,实际上,我无法停止程序或它停止写入文本文件,我想定期读出当前在另一个程序中的文本文件中的内容).

In VB.NET or C#, I'm trying to read the contents of a text file that is in use by another program (that's the point, actually, I can't stop the program or it stops writing to the text file, and I want to periodically read out what is currently in the text file in another program).

这是我使用的代码(VB.NET)

This is the code I'm using (VB.NET)

Dim strContents As String
Dim objReader As StreamReader
objReader = New StreamReader(FullPath)
strContents = objReader.ReadToEnd()
objReader.Close()

或在 C# 中:

var objReader = new StreamReader(FullPath);
var strContents = objReader.ReadToEnd();
objReader.Close();

然而,上面会抛出 IO 异常进程无法访问文件 'file.txt',因为它正被另一个进程使用."在这种情况下是否有任何解决方法?

The above, however, throws the IO exception "The process cannot access the file 'file.txt' because it is being used by another process." Are there any workarounds in this scenario?

推荐答案

FileStream logFileStream = new FileStream("c:	est.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
StreamReader logFileReader = new StreamReader(logFileStream);

while (!logFileReader.EndOfStream)
{
    string line = logFileReader.ReadLine();
    // Your code here
}

// Clean up
logFileReader.Close();
logFileStream.Close();

原始代码来源

这篇关于即使“正在被另一个进程使用",我如何读取文件?例外?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆