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
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
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.
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))
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;
}
use an overload of File.Open in your menuclick event handler like this:
The last param is a value specifying the type of access other threads have to the file.
see this article from msdn