3

I need to read a text based log file to check for certain contents (the completion of a backup job). Obviously, the file is written to when the job completes.

My question is, how can I (or how SHOULD I write the code to) read the file, taking into account the file may be locked, or locked by my process when it needs to be read, without causing any reliability concerns.

AgentAkki
  • 39
  • 5
GurdeepS
  • 65,107
  • 109
  • 251
  • 387

3 Answers3

3

Assuming the writing process has at least specified System.IO.FileShare.Read when opening the file, you should be able to read the text file while it is still being written to.

BrokenGlass
  • 158,293
  • 28
  • 286
  • 335
3

In addition to the answer by @BrokenGlass:

  • Only open the file for reading. If you try to open it for Read/Write access, it's more likely (almost certain) to fail - you may not be able to open it, and/or you may stop the other process being able to write to it.

  • Close the file when you aren't reading it to minimise the chance that you might cause problems for any other processes.

  • If the writing process denies read access while it is writing to the file, you may have to write some form of "retry loop", which allows your application to wait (keep retrying) until the file becomes readable. Just try to open the file (and catch errors) - if it fails, Sleep() for a bit and then try again. (However, if you're monitoring a log file, you will probbably want to keep checking it for more data anyway)

Jason Williams
  • 56,972
  • 11
  • 108
  • 137
-1

When a file is being written to, it is locked for all other processes that try to open the file in Write-mode. Read-mode will always be available.

However, if your writing process saves changes while you have already opened the file in your reading process, the changes will not be reflected there until you refresh (Close-Open) the file again.

Flater
  • 12,908
  • 4
  • 39
  • 62
  • Read sharing is NOT guaranteed to always be available - it depends on whether the writer has specified read sharing. – Polyfun Dec 30 '11 at 14:27
  • If you specifically disabled read access yes. But if that is a given, then this whole question seems rather pointless? – Flater Jan 02 '12 at 08:41