How to Easily Check If Access Is Denied For a File in .Net

How can i check for access denied when getting files?

Few suggestions for you

  • You should enclose the read process inside a try.. catch block. so that Access-Denied Exception will throw if the specified file is not accessible.
  • use restrictedFiles to Keep Track of the skipped files.
  • Use continue; in catch to continue the iteration.

Let me rename the variables as well for better understanding; Now consider the code

void DirSearch(string rootDirectory, string filesExtension, string textToSearch, BackgroundWorker worker, DoWorkEventArgs e)
{
List<string> filePathList = new List<string>();
List<string> restrictedFiles = new List<string>();
// Other Inits
try
{
filePathList = Directory.GetFiles(rootDirectory, filesExtension, SearchOption.AllDirectories).ToList();
}
catch (Exception err)
{
string ad = err.ToString();
}
foreach (string file in filePathList)
{
try
{
// Code before
int var = File.ReadAllText(file).Contains(textToSearch) ? 1 : 0;
// it will throw exception if it is not accessible
// Your code after
}
catch (Exception)
{
restrictedFiles.Add(file);
continue;
}
}
// restrictedFiles will contains all restricted files @ the end of iteration
}

How do I check if an access to a string path is denied?

The simplest (and usually safest) option is to just do what you're doing now, but wrap the code in proper exception handling.

You can then catch the UnauthorizedAccessException from GetFiles (and potentially a SecurityException from the DirectoryInfo constructor, depending on the path) explicitly, and put your handling logic there.

ASP.Net file uploade has error Access Denied

Right-Click the folder, go to Properties, Security tab, make sure the local ASPNET account has Read and Write permissions on that folder. If not, Add local ASPNET account to the list and give it read and write permissions. Click OK.

Update:

It's beacause the problem is that ASPNET user or NETWORK SERVICE user (both are user accounts on the server, which ASPNET uses to authorize for the OS) need to have permissions to write the file to aforementioned location.

Account need the permissions to the folder where file is written (the file isn't there before uploading, of course), so user of course doesn't set any permissions to anywhere but server admninistrator does to 'D:\inetpub\mywebfolder\subfoldername dir in this case (I might suggest specifying a location outside web folders in case they are not supposed to be downloaded just like that)

Writing something is stronger permission than just reading so, admin needs to give the write permission in order to enable file uploading if you want to save it straight to server's hard disk.

Access denied error when writing a text file into the ftproot folder based on file type

Caius was actually very close to the answer! There were no programs that had the file open but somehow in the initial application creation, I created a hidden file with the same name. When I turned on hidden files, I saw it.

Checking file/folder access permission

First of all, I would manually check the permissions and see what blocks you and what doesn't. I am using something like this to check for permissions (for copy file):

AuthorizationRuleCollection acl = fileSecurity.GetAccessRules(true, true,typeof(System.Security.Principal.SecurityIdentifier));
bool denyEdit = false;
for (int x = 0; x < acl.Count; x++)
{
FileSystemAccessRule currentRule = (FileSystemAccessRule)acl[x];
AccessControlType accessType = currentRule.AccessControlType;
//Copy file cannot be executed for "List Folder/Read Data" and "Read extended attributes" denied permission
if (accessType == AccessControlType.Deny && (currentRule.FileSystemRights & FileSystemRights.ListDirectory) == FileSystemRights.ListDirectory)
{
//we have deny copy - we can't copy the file
denyEdit = true;
break;
}
... more checks
}

Also, there are some strange cases where a certain right on the folder changes the right for the files regardless of their individual permissions (will see if I can find what it is).

File.Exists acts differently when access is denied to the file vs denied to the dir

That is the default behavior of the File.Exist. According to MSDN:

File.Exist

Return Value Type: System.Boolean

true if the caller has
the required permissions and path contains the name of an existing
file; otherwise, false. This method also returns false if path is
null, an invalid path, or a zero-length string. If the caller does not
have sufficient permissions to read the specified file, no exception
is thrown and the method returns false regardless of the existence of
path.

And additionally

The Exists method should not be used for path validation, this method
merely checks if the file specified in path exists. Passing an invalid
path to Exists returns false.

In other words, the required permission here, is the required permission to know the existence of the file (as the method name implies, File.Exist). And this means that as long as a user has access to the directory, it can know if the file exists or not.

Whether the user has file access or not doesn't affect the user's knowledge of the existence of the file, given the directory permission. But without directory permission, a user cannot know the existence of the file, and thus File.Exist returns false


Edit (after feedback from comments):

And probably the rather confusing part would be the last sentence:

If the caller does not
have sufficient permissions to read the specified file, no exception
is thrown and the method returns false regardless of the existence of
path.

The sufficient permissions to read the specified file is depending on the read-access of the parent directory rather than read-access of the specified file. (Additional comment by Mr. Rob). The word "sufficient" may give some hint about the behavior that it will only depend on read-access to the parent directory is needed, not the read-access to the specified file.

But I admit that the explanation and the choice of word may sound rather counter-intuitive as people may intuitively interpret "sufficient permissions to read the specified file" as the read-access to the specified file rather than to the parent directory.

Checking for directory and file write permissions in .NET

The answers by Richard and Jason are sort of in the right direction. However what you should be doing is computing the effective permissions for the user identity running your code. None of the examples above correctly account for group membership for example.

I'm pretty sure Keith Brown had some code to do this in his wiki version (offline at this time) of The .NET Developers Guide to Windows Security. This is also discussed in reasonable detail in his Programming Windows Security book.

Computing effective permissions is not for the faint hearted and your code to attempt creating a file and catching the security exception thrown is probably the path of least resistance.

Files: how to distinguish file lock and permission denied cases?

As per my answer here: Is there a way to check if a file is in use?

const int ERROR_SHARING_VIOLATION = 32;
const int ERROR_LOCK_VIOLATION = 33;

private static bool IsFileLocked(Exception exception)
{
int errorCode = Marshal.GetHRForException(exception) & ((1 << 16) - 1);
return errorCode == ERROR_SHARING_VIOLATION || errorCode == ERROR_LOCK_VIOLATION;
}

...

FileStream stream = null;
try
{
stream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
}
catch (IOException ex)
{
if (IsFileLocked(ex))
{
// you know the file is locked
}
}
catch (ArgumentNullException ex)
{
HandleException(ex);
}
catch (SecurityException ex)
{
HandleException(ex);
}
catch (ArgumentException ex)
{
HandleException(ex);
}
catch (ObjectDisposedException ex)
{
HandleException(ex);
}
catch (UnauthorizedAccessException ex)
{
// you know you dont have permission to the file
HandleException(ex);
}
catch (Exception ex)
{
}


Related Topics



Leave a reply



Submit