How do you read a file which is in use? [duplicate]
I have a small problem. I have a tool which should parse a log file daily, unfortunately this log file is in use by the process which writes to the log and I cannot stop it.
First try was to create a copy of the file, which is not working either.
Is there any way for me to read the current text of the log file, even if it is already in use?
Solution 1:
using (FileStream stream = File.Open("path to file", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (StreamReader reader = new StreamReader(stream))
{
while (!reader.EndOfStream)
{
}
}
}
The FileAccess specifies what YOU want to do with the file. The FileShare specifies what OTHERS can do with the file while you have it in use.
In the example above, you can open a file for reading while other processes can have the file open for read/write access. In most cases, this will work for opening logfiles that are in use.
Solution 2:
You are at the mercy of the program that is writing the file. In Windows, a process can open a file for reading, writing or both, but it can also control whether other processes can open the file for reading, writing or both. If the other process has denied you the right to read the contents of the file, then there is nothing you can do about it.
If you control the source code of the program that is writing the log file, then change it to allow read access by other processes.
Solution 3:
Use File.OpenRead(path)
, this allows you to access a readonly stream to the file; that way you won't be bothered if another application has a write lock on the file.