Checking for Directory and File Write Permissions in .Net

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.

Checking if a directory has read and write permissions using .Net Core

FileIOPermission is part of .NET's code security - it's meant to allow you to host .NET code that has lower permissions than the host process (i.e. software process isolation). It doesn't have anything to do with the file system's access rights.

For .NET Core, you can read and modify access control to files with the System.IO.FileSystem.AccessControl package. After adding the package, you can do something like this:

using System.IO;

public void Main(string[] args)
{
var ac = new FileInfo(@"C:\Test.txt").GetAccessControl();

// ac has the ACL for the file
}

Needless to say, this is Windows specific.

Check if directory exists and Permissions

Well try creating the directory or the file and if you don't have permission an exception would be thrown which you can catch and do as needed.

try
{
// code to create directory or file
}
catch(Exception ex)
{
// do something here
}

How do you check for permissions to write to a directory or file?

UPDATE:

Modified the code based on this answer to get rid of obsolete methods.

You can use the Security namespace to check this:

public void ExportToFile(string filename)
{
var permissionSet = new PermissionSet(PermissionState.None);
var writePermission = new FileIOPermission(FileIOPermissionAccess.Write, filename);
permissionSet.AddPermission(writePermission);

if (permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet))
{
using (FileStream fstream = new FileStream(filename, FileMode.Create))
using (TextWriter writer = new StreamWriter(fstream))
{
// try catch block for write permissions
writer.WriteLine("sometext");


}
}
else
{
//perform some recovery action here
}

}

As far as getting those permission, you are going to have to ask the user to do that for you somehow. If you could programatically do this, then we would all be in trouble ;)

C# Test if user has write access to a folder

That's a perfectly valid way to check for folder access in C#. The only place it might fall down is if you need to call this in a tight loop where the overhead of an exception may be an issue.

There have been other similar questions asked previously.

How to check Read and write permissions on folder in C#

How to check read and write permission on a folder

string folder = ...

var permission = new FileIOPermission(FileIOPermissionAccess.Write, folder);
var permissionSet = new PermissionSet(PermissionState.None);
permissionSet.AddPermission(permission);
if (permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet))
{
// You have write permission for the given folder
}

How to create an html file on runtime in project root

string file = Path.Combine(Server.MapPath("~/"), "foo.html");
File.WriteAllText(file, "<html><body><h1>Hello</h1></body></html>");

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).

In .NET, check that the current user may write to a directory

FileIOPermission writePermission = new FileIOPermission(FileIOPermissionAccess.Write, filename);
if (SecurityManager.IsGranted(writePermission)){
//write here
} else {
//some error message
}


Related Topics



Leave a reply



Submit