how can you easily check if access is denied for a file in .NET?

后端 未结 6 545
无人及你
无人及你 2020-11-22 14:13

Basically, I would like to check if I have rights to open the file before I actually try to open it; I do not want to use a try/catch for this check unless I have to. Is the

6条回答
  •  野性不改
    2020-11-22 14:59

    public static FileStream GetFileStream(String filePath, FileMode fileMode, FileAccess fileAccess, FileShare fileShare, ref int attempts, int attemptWaitInMilliseconds)
    {            
        try
        {
             return File.Open(filePath, fileMode, fileAccess, fileShare);
        }
        catch (UnauthorizedAccessException unauthorizedAccessException)
        {
            if (attempts <= 0)
            {
                throw unauthorizedAccessException;
            }
            else
            {
                Thread.Sleep(attemptWaitInMilliseconds);
                attempts--;
                return GetFileStream(filePath, fileMode, fileAccess, fileShare, ref attempts, attemptWaitInMilliseconds);
            }
        }
    }
    

提交回复
热议问题