Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you read a file which is in use? [duplicate]

Tags:

c#

file-io

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?

like image 788
Feroc Avatar asked Sep 14 '10 13:09

Feroc


People also ask

What does it mean when it says duplicate files?

A duplicate is anything that is an exact copy of another thing. For example, with computers, a duplicate file is an exact copy of a file.

How do I remove duplicate lines in files?

Remove duplicate lines with uniq If you don't need to preserve the order of the lines in the file, using the sort and uniq commands will do what you need in a very straightforward way. The sort command sorts the lines in alphanumeric order. The uniq command ensures that sequential identical lines are reduced to one.


2 Answers

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.

like image 64
Tom Vervoort Avatar answered Sep 19 '22 06:09

Tom Vervoort


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.

like image 30
Christian Hayter Avatar answered Sep 18 '22 06:09

Christian Hayter