我正在尝试读取某些程序正在使用的所有日志文件行。
当我尝试这样做时,我收到了异常:
System.IO.IOException was unhandled : file used by another process
所以我在网上搜索并找到了许多解决方案:
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
。
我尝试了这些解决方案,但我仍然收到另一个进程正在使用该文件的异常。
在我的下面的代码中,我打开文件D:\process.log
以使用该文件(进行测试),然后尝试打开该文件。
行例外:
using (FileStream fileStream = File.Open(i_FileNameAndPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
CODE:
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;
}
答案 0 :(得分:4)
在menuclick事件处理程序中使用File.Open的重载,如下所示:
File.Open(@"C:\process.log", FileMode.Open,FileAccess.ReadWrite, FileShare.ReadWrite);
最后一个参数是一个值,用于指定其他线程对文件的访问类型。