There are several ways to read information from a file. At the same time, if the file is occupied by another process, an exception will be thrown.

The exception can of course be caught, but if this is unacceptable, what can be done?

The situation is this: using FileSystemWatcher to read the file after the change, the change will most likely be made from notepad. If immediately after the change event you try to read the file, then the notepad process will still use it and it will not have time to release access, we will get an exception in most cases.

For a start, I would like to understand how you can check the availability of a file reading before reading it, so as not to catch the exception.

  • You can try to read in a loop until it is read, pausing after an exception occurs. - Vladimir Gamalyan
  • And CreateFile with the "read" flag will not return an Invalid handle if the file is still busy and cannot be opened? - Vladimir Martyanov
  • You can’t find out by any checks whether the file will be available for reading by the time you open it . Exceptions can not be avoided. Welcome to the real world. - VladD
  • one

1 answer 1

You do not need to set a task "not to catch an exception" - you need to catch an exception and try again.

When I had a similar task, a pause of 100 milliseconds showed itself well after receiving an event before any actions with the file - as a rule, during this time the file managed to free itself, but the user is usually not aware of such a pause.

  • Yes, I also tried to do it and it worked. I decided to learn less clumsy ways, but something tells me that they are not. - anweledig
  • I understand that in Sharp it is impossible to read and write files with locks from several processes, what is the norm for other languages? - vitidev 2:21 pm
  • @vitidev file access lock is provided by the operating system. The language has nothing to do with it. - Pavel Mayorov
  • @vitidev: Nowhere is it possible. The file on the CD, after checking the CD out, an exception. The file on the network drive, after checking the server fell off, an exception. The file on the local disk, after checking the account LOCAL SYSTEM renamed the file, an exception. You can’t avoid catching an exception; it’s out of the programmer’s control. - VladD
  • @PavelMayorov in php for example, there is adviosory locking for files (LOCK_EX, LOCK_SH), which allows you to read a lot and write exclusively under Windows as well. And how to do this in a c #? ReaderWriterLock is not like that. - vitidev