0

There is a file C:\acme.log that another program (not mine) is writing to. It is a log file, so the program always has it open for writing.

I would like to read the current contents of the log file. I tried

FileInfo fInfo = new FileInfo(@"C:\acme.log");
FileStream fileStream = fInfo.Open(FileMode.Open, FileAccess.Read);

This fails with System.IO.IOException: The process cannot access the file 'C:\acme.log' because it is being used by another process.

I can open the file in Notepad and view its contents. If Notepad can open the file, there should be a way for my program to do it, shouldn't there?

George
  • 2,436
  • 4
  • 15
  • 30
  • check out [File.OpenRead](https://learn.microsoft.com/en-us/dotnet/api/system.io.file.openread?redirectedfrom=MSDN&view=netframework-4.7.2#System_IO_File_OpenRead_System_String_) – Adam Vincent Nov 08 '18 at 15:20

1 Answers1

1

See the link here:

Reading a file which is locked by another process

Here is the code from that link:

using (FileStream logFileStream = new FileStream("c:\test.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (StreamReader logFileReader = new StreamReader(logFileStream))
{

   while (!logFileReader.EndOfStream)
   {
      string line = logFileReader.ReadLine();
      // Your code here
   }
}
hcham1
  • 1,799
  • 2
  • 16
  • 27
  • 5
    Do not `Close` explicitly, but wrap into `using` i.e. `using (FileStream logFileStream = ...) {...}` – Dmitry Bychenko Nov 08 '18 at 15:22
  • @DmitryBychenko , could you elaborate more why you would rather use a `using` statement instead of explicitly closing? Do they not achieve the same? – Jaskier Nov 08 '18 at 15:26
  • Thank you. FileShare.ReadWrite seems to be the ticket. Instead of using this code, I added the flag to my code which seems to fix it. – George Nov 08 '18 at 15:28
  • 2
    @Symon: if `new StreamReader(logFileStream)` or`logFileReader.ReadLine()` *throws exception* `logFileStream.Close()` will *not* be executed and and thus stream will not be closed (we'll have *resource leakage*) – Dmitry Bychenko Nov 08 '18 at 15:28
  • @DmitryBychenko Thanks for your suggestions, I updated the code to use using statements – hcham1 Nov 08 '18 at 18:59