Reputation: 109
I am trying to check if a directory has read and write permissions using .Net Core.
I am using Visual Studio 2019, .Net Core 2.1. I have tried GetAccessControl with no luck, so tried the following.
public static bool DirectoryHasPermission(string DirectoryPath)
{
if (string.IsNullOrEmpty(DirectoryPath))
{
return false;
}
FileIOPermission f2 = new FileIOPermission(FileIOPermissionAccess.Read, DirectoryPath);
f2.AddPathList(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, "C:\\example\\out.txt");
try
{
f2.Demand();
}
catch (SecurityException s)
{
Console.WriteLine(s.Message);
return false;
}
return true;
}
No matter what directory path I put in, even if it doesn't exist it returns true.
Upvotes: 0
Views: 9003
Reputation: 63772
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.
Upvotes: 4