Как обрабатывать UnauthorizedAccessException при запуске FileSystemWatcher - PullRequest
0 голосов
/ 22 мая 2019

Я получаю сообщение об ошибке при запуске FileSystemWatcher для пути, который содержит недоступную папку.Папка недоступна даже для файловой системы, если я пытаюсь получить к ней доступ, я получаю всплывающее сообщение с просьбой предоставить постоянный доступ моему пользователю, это вполне нормально, но я бы хотел обработать ее в моем приложении, чтобы правильно запуститьwatcher.

_watcher = new FileSystemWatcher(_path, _filter)
{
    IncludeSubdirectories = true,
    NotifyFilter = NotifyFilters.LastAccess
                   | NotifyFilters.LastWrite
                   | NotifyFilters.FileName
                   | NotifyFilters.DirectoryName
};


_watcher.Changed += new FileSystemEventHandler(OnChanged);
_watcher.Created += new FileSystemEventHandler(OnCreated);
_watcher.Deleted += new FileSystemEventHandler(OnDeleted);
_watcher.Renamed += new RenamedEventHandler(OnRenamed);


_watcher.EnableRaisingEvents = true;

Исключение, которое я получаю, это

UnauthorizedAccessException: Access to the path 'D:\some_folder' is denied.
System.IO.__Error.WinIOError (System.Int32 errorCode, System.String maybeFullPath) (at <e1a80661d61443feb3dbdaac88eeb776>:0)
System.IO.FileSystemEnumerableIterator`1[TSource].HandleError (System.Int32 hr, System.String path) (at <e1a80661d61443feb3dbdaac88eeb776>:0)
System.IO.FileSystemEnumerableIterator`1[TSource].CommonInit () (at <e1a80661d61443feb3dbdaac88eeb776>:0)
System.IO.FileSystemEnumerableIterator`1[TSource]..ctor (System.String path, System.String originalUserPath, System.String searchPattern, System.IO.SearchOption searchOption, System.IO.SearchResultHandler`1[TSource] resultHandler, System.Boolean checkHost) (at <e1a80661d61443feb3dbdaac88eeb776>:0)
System.IO.FileSystemEnumerableFactory.CreateFileNameIterator (System.String path, System.String originalUserPath, System.String searchPattern, System.Boolean includeFiles, System.Boolean includeDirs, System.IO.SearchOption searchOption, System.Boolean checkHost) (at <e1a80661d61443feb3dbdaac88eeb776>:0)
System.IO.Directory.InternalGetFileDirectoryNames (System.String path, System.String userPathOriginal, System.String searchPattern, System.Boolean includeFiles, System.Boolean includeDirs, System.IO.SearchOption searchOption, System.Boolean checkHost) (at <e1a80661d61443feb3dbdaac88eeb776>:0)
System.IO.Directory.InternalGetDirectories (System.String path, System.String searchPattern, System.IO.SearchOption searchOption) (at <e1a80661d61443feb3dbdaac88eeb776>:0)
System.IO.Directory.GetDirectories (System.String path) (at <e1a80661d61443feb3dbdaac88eeb776>:0)
System.IO.DefaultWatcher.DoFiles (System.IO.DefaultWatcherData data, System.String directory, System.Boolean dispatch) (at <4b9f316768174388be8ae5baf2e6cc02>:0)
System.IO.DefaultWatcher.DoFiles (System.IO.DefaultWatcherData data, System.String directory, System.Boolean dispatch) (at <4b9f316768174388be8ae5baf2e6cc02>:0)
System.IO.DefaultWatcher.DoFiles (System.IO.DefaultWatcherData data, System.String directory, System.Boolean dispatch) (at <4b9f316768174388be8ae5baf2e6cc02>:0)
System.IO.DefaultWatcher.DoFiles (System.IO.DefaultWatcherData data, System.String directory, System.Boolean dispatch) (at <4b9f316768174388be8ae5baf2e6cc02>:0)
System.IO.DefaultWatcher.DoFiles (System.IO.DefaultWatcherData data, System.String directory, System.Boolean dispatch) (at <4b9f316768174388be8ae5baf2e6cc02>:0)
System.IO.DefaultWatcher.DoFiles (System.IO.DefaultWatcherData data, System.String directory, System.Boolean dispatch) (at <4b9f316768174388be8ae5baf2e6cc02>:0)
System.IO.DefaultWatcher.DoFiles (System.IO.DefaultWatcherData data, System.String directory, System.Boolean dispatch) (at <4b9f316768174388be8ae5baf2e6cc02>:0)
System.IO.DefaultWatcher.UpdateDataAndDispatch (System.IO.DefaultWatcherData data, System.Boolean dispatch) (at <4b9f316768174388be8ae5baf2e6cc02>:0)
System.IO.DefaultWatcher.StartDispatching (System.IO.FileSystemWatcher fsw) (at <4b9f316768174388be8ae5baf2e6cc02>:0)
System.IO.FileSystemWatcher.Start () (at <4b9f316768174388be8ae5baf2e6cc02>:0)
System.IO.FileSystemWatcher.set_EnableRaisingEvents (System.Boolean value) (at <4b9f316768174388be8ae5baf2e6cc02>:0)
(wrapper remoting-invoke-with-check) System.IO.FileSystemWatcher.set_EnableRaisingEvents(bool)

Пути существуют, они находятся внутри ключа usb, для которого у меня есть разрешения на чтение / запись, это только конкретныйпапка, которая поднимает проблему.Есть ли способ безопасно перехватить это исключение и запустить наблюдателя?

1 Ответ

0 голосов
/ 22 мая 2019

Вы можете сначала проверить разрешения:

public static bool HasWritePermissionOnDir(string path)
{
    var writeAllow = false;
    var writeDeny = false;
    var accessControlList = Directory.GetAccessControl(path);
    if (accessControlList == null)
        return false;
    var accessRules = accessControlList.GetAccessRules(true, true, 
                                typeof(System.Security.Principal.SecurityIdentifier));
    if (accessRules ==null)
        return false;

    foreach (FileSystemAccessRule rule in accessRules)
    {
        if ((FileSystemRights.Write & rule.FileSystemRights) != FileSystemRights.Write) 
            continue;

        if (rule.AccessControlType == AccessControlType.Allow)
            writeAllow = true;
        else if (rule.AccessControlType == AccessControlType.Deny)
            writeDeny = true;
    }

    return writeAllow && !writeDeny;
}
...