- 1 year ago
How to get the permissions from shared folder using C#?
To get the permissions from a shared folder using C#, you can use the DirectoryInfo
class from the System.IO
namespace. Here's an example:
csharpusing System;
using System.IO;
using System.Security.AccessControl;
class Program
{
static void Main()
{
string folderPath = @"\\server\shared-folder";
try
{
DirectoryInfo directoryInfo = new DirectoryInfo(folderPath);
DirectorySecurity directorySecurity = directoryInfo.GetAccessControl();
AuthorizationRuleCollection accessRules = directorySecurity.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));
Console.WriteLine($"Permissions for folder: {folderPath}");
Console.WriteLine("-------------------------------------");
foreach (FileSystemAccessRule rule in accessRules)
{
Console.WriteLine($"User/Group: {rule.IdentityReference}");
Console.WriteLine($"Permissions: {rule.FileSystemRights}");
Console.WriteLine($"Access Type: {rule.AccessControlType}");
Console.WriteLine();
}
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
Console.ReadLine();
}
}
In this example, folderPath
represents the path to the shared folder you want to retrieve permissions from. The program uses the DirectoryInfo
class to obtain the directory's information and the GetAccessControl
method to retrieve the security information for the folder. The GetAccessRules
method is then used to retrieve the access rules for the folder, and the program prints out the user/group, permissions, and access type for each rule.
Make sure to run the program with appropriate permissions, as accessing security information may require administrative privileges or proper access rights to the shared folder.
Remember to include the necessary using
statements at the beginning of your code file:
csharpusing System;
using System.IO;
using System.Security.AccessControl;
You can customize the code further based on your requirements, such as filtering specific users or groups or formatting the output as needed.