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?
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(); } // Файл не открыт в стороннем процессе ReadAllBytes is brute force. According to the law of meanness, there will definitely be a film in HD for tens of GB ... - Alexander PetrovSource: https://ru.stackoverflow.com/questions/691962/
All Articles
None- another process will not be able to open it. - Alexander PetrovFileShare.ReadWrite | FileShare.DeleteFileShare.ReadWrite | FileShare.Delete. - Alexander Petrov