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?
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.
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.
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.
it depends, have you tried reading the file in read only? using one of the static methods
System.IO.File.ReadAllText(path) or System.IO.File.ReadAllLines(path)
they may work if there file isn't locked exclusively
I highly recommend BareTail, which we use to look at all of our logs in real time. Also supports highlighting, which is very useful.
精彩评论