Check file Permission in C# .NET Core

Viewed 1926

I'm working on a project where I have to perform sanity checks on files. I need to make sure the current system user has read access to the file, and I first tried doing it with:

var readPermission = new FileIOPermission(FileIOPermissionAccess.Read, filePath);

try
{
    readPermission.Demand();
}
catch (SecurityException ex)
{
    //handle the exception, which should be thrown if current user does NOT have the read permission
}

That did not work, e.g. no exception was thrown, and so i tried doing this:

var readPermission = new FileIOPermission(FileIOPermissionAccess.Read, filePath);


if(! SecurityManager.IsGranted(readPermission))
{

    throw new SecurityException(
        String.Format("System user: {0} does not have read access to file {1}", User.Identity.Name, filePath)
        );
}

the SecurityManager api seems to be mostly deprecated however, So that also seems like a dead end. Is there some other way to tell what permissions a user has to a file?

1 Answers
  • First, get Access control list (ACL) entries for the file described by the current FileInfo object, this is encapsulated in FileSecurity object
  • We then use GetAccessRules that gets a collection of the rules associated with aforementioned FileSecurity object
  • The Collection of rules represents AuthorizationRule objects which FileSystemAccessRule derives from, which you can interrogate to understand permission pertaining to the file

Snippet: Checks if test.txt has Read permissions (Has been tested using .Net Core)

using System;
using System.IO;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Linq;

var MyPath = @"C:\Users\repos\test.txt";
var fInfo = new FileInfo(MyPath);

FileSecurity fSecurity = fInfo.GetAccessControl();

SecurityIdentifier usersSid = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
FileSystemRights fileRights = FileSystemRights.Read | FileSystemRights.Synchronize; //All read only file usually have Synchronize added automatically when allowing access, refer the msdn doc link below

var rules = fSecurity.GetAccessRules(true, true, usersSid.GetType()).OfType<FileSystemAccessRule>();
var hasRights = rules.Where(r => r.FileSystemRights == fileRights).Any();

Nuget Prerequisite: System.IO.FileSystem.AccessControl

Reference: FileSystemRights Enums

Related