无法读取文件中被另一进程使用的所有行 [英] Can't read all lines in file that being used by another process
问题描述
我正在尝试读取某些程序正在使用的日志文件的所有行.
I am trying to read all lines of log file that being used by some program.
当我尝试执行此操作时,我收到异常:
When I tried to do it I am receiving exception:
System.IO.IOException was unhandled : file used by another process
因此我在网上搜索并找到了许多解决方案:
C#异常.文件正在被另一个进程使用
读取另一个进程正在使用的日志文件
用C#(也许在不安全模式下)读取锁定文件的侵入性最小的方法是什么?
C#进程无法访问文件''',因为它正在被另一个进程使用
文件正在被另一个进程使用
So I searched on the web and found number of solutions:
C# exception. File is being used by another process
Read log file being used by another process
What's the least invasive way to read a locked file in C# (perhaps in unsafe mode)?
C# The process cannot access the file ''' because it is being used by another process
File is being used by another process
http://coding.infoconex.com/post/2009/04/21/How-do-I-open-a-file-that-is-in-use-in-C
常见的解决方案是使用using
包裹FileStream
并添加FileShare.ReadWrite
.
The common solutions are to use using
to wrap the FileStream
and add the FileShare.ReadWrite
.
我尝试了这些解决方案,但仍然收到另一个文件正在使用该文件的例外.
I tried those solutions but I am still receiving the exception that the file is being used by another process.
在下面的代码中,我打开文件D:\process.log
以使该文件使用(用于测试),然后尝试打开该文件.
例外是在行上:
In my below code I open the file D:\process.log
to make the file used (for testing) and then trying to open the file.
The exception is on row:
using (FileStream fileStream = File.Open(i_FileNameAndPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
代码:
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
DialogResult dialogResult = openFileDialog.ShowDialog();
if (dialogResult == DialogResult.OK)
{
listView.Items.Clear();
File.Open(@"D:\process.log", FileMode.Open); //make the file being used
String fileNameAndPath = openFileDialog.FileName;
String[] fileContent = readAllLines(fileNameAndPath);
}
}
private String[] readAllLines(String i_FileNameAndPath)
{
String[] o_Lines = null;
int i = 0;
using (FileStream fileStream = File.Open(i_FileNameAndPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (StreamReader streamReader = new StreamReader(fileStream))
{
while (streamReader.Peek() > -1)
{
String line = streamReader.ReadLine();
//o_Lines[i] = line;
i++;
}
}
}
return o_Lines;
}
推荐答案
使用File的重载.在菜单单击事件处理程序中像这样打开:
use an overload of File.Open in your menuclick event handler like this:
File.Open(@"C:\process.log", FileMode.Open,FileAccess.ReadWrite, FileShare.ReadWrite);
最后一个参数是一个值,用于指定其他线程对该文件的访问类型.
The last param is a value specifying the type of access other threads have to the file.
请参见 查看全文