It is necessary to open if the file is now open in other processes.

The essence of the program does not allow opening files that are used in other processes. Still need to ban open files if it is used in my program.

How can this be done?

  • one
    See FileShare : open the file with the value None - another process will not be able to open it. - Alexander Petrov
  • one
    To find out if a file is open in other processes, you can try to open it and read / write / delete - if something fails, it means open. But it will not work if it is opened by another process with FileShare.ReadWrite | FileShare.Delete FileShare.ReadWrite | FileShare.Delete . - Alexander Petrov

1 answer 1

This suggests a solution that returns true / false depending on whether the file is open in third-party software or not.

I would like to immediately warn against this approach: the fact is that the file may not be open, but with it (with the file) there may be much more "interesting" problems (for example, this file may not exist in a banal way) .

In this regard, the issue requires a more comprehensive approach: for example, in the example below, an attempt is made to open a file for reading, and, in the event of an error, to analyze it.

Extension for Exception (of course, if necessary, easily converted to a function):

 public static class ExceptionExtension { private const int ERROR_SHARING_VIOLATION = 32; private const int ERROR_LOCK_VIOLATION = 33; public static bool IsFileLocked(this Exception exception) { int errorCode = Marshal.GetHRForException(exception) & ((1 << 16) - 1); return errorCode == ERROR_SHARING_VIOLATION || errorCode == ERROR_LOCK_VIOLATION; } } 

Using:

  FileStream fs = null; try { fs = System.IO.File.Open(filePath, FileMode.Open); // Пробуем открыть файл на чтение // ...или сразу читаем содержимое (при необходимости предварительно проверяем файл на размер) //byte[] fileBytes = System.IO.File.ReadAllBytes(filePath); } catch (Exception ex) { if (ex.IsFileLocked) { // Файл открыт в стороннем процессе throw; } else { // Произошла иная ошибка доступа к файлу throw; } } finally { fs?.close(); } // Файл не открыт в стороннем процессе 
  • one
    ReadAllBytes is brute force. According to the law of meanness, there will definitely be a film in HD for tens of GB ... - Alexander Petrov
  • @AlexanderPetrov I agree with you, slightly changed the answer - Pavel Dmitrenko