c# View folder permissions - c#

I can search folder permissions using cacls.exe with command prompt and output them to a text file but I need to display the folder permissions within the C# program so that i can use them in strings etc.

DirectorySecurity dSecurity = Directory.GetAccessControl(#"d:\myfolder");
foreach (FileSystemAccessRule rule in dSecurity.GetAccessRules(true, true, typeof(NTAccount)))
{
if (rule.FileSystemRights == FileSystemRights.Read)
{
Console.WriteLine("Account:{0}", rule.IdentityReference.Value);
}
}

Related

C# DirectorySecurity SetOwner on subcontainers and objects

I am trying to change ownership of a windows folder and everything inside it. Basially I am trying to check the box that would be there if you did this manually in windows that says "Replace owner on subcontainers and objects". This will need to work over a network share path. I am able to get 1 folder deep but then it just stops there. This does not include the base folder changing either.
foreach (string directory in Directory.GetDirectories(dirPath))
{
var di = new DirectoryInfo(directory);
IdentityReference user = new NTAccount(Login.authUserName.ToString());
DirectorySecurity dSecurity = di.GetAccessControl();
dSecurity.SetOwner(user);
di.SetAccessControl(dSecurity);
}
You can use Directory.GetDirectories with SearchOption.AllDirectories in order to recurse.
But it seems easier to just get the DirectoryInfo di objects directly using DirectoryInfo.GetDirectories, which has the same and more recursive options.
IdentityReference user = new NTAccount(Login.authUserName.ToString());
var root = new DirectoryInfo(dirPath);
foreach (var di in root.GetDirectories("*", SearchOption.TopDirectoryOnly).Prepend(root))
{
var dSecurity = di.GetAccessControl();
dSecurity.SetOwner(user);
di.SetAccessControl(dSecurity);
}

how to check if specific user having access to a shared folder location using C#

We have a scenario in our client project where the client application saves and tries to fetch files from a shared folder location , which is a virtual shared folder. But we have been facing issues with a specific application user id losing access to that shared folder. So we need help in pre advance checking if the access is present for that user id on that shared folder location . So thinking of an application to be developed in C# or vb.net to check for that user access .
the way I believe best to check the permission, is try to access the directory (read/write/list) & catch the UnauthorizedAccessException.
If you want to check permissions, following code should satisfy your need. You need to read Access Rules for the directory.
private bool DirectoryCanListFiles(string folder)
{
bool hasAccess = false;
//Step 1. Get the userName for which, this app domain code has been executing
string executingUser = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
NTAccount acc = new NTAccount(executingUser);
SecurityIdentifier secId = acc.Translate(typeof(SecurityIdentifier)) as SecurityIdentifier;
DirectorySecurity dirSec = Directory.GetAccessControl(folder);
//Step 2. Get directory permission details for each user/group
AuthorizationRuleCollection authRules = dirSec.GetAccessRules(true, true, typeof(SecurityIdentifier));
foreach (FileSystemAccessRule ar in authRules)
{
if (secId.CompareTo(ar.IdentityReference as SecurityIdentifier) == 0)
{
var fileSystemRights = ar.FileSystemRights;
Console.WriteLine(fileSystemRights);
//Step 3. Check file system rights here, read / write as required
if (fileSystemRights == FileSystemRights.Read ||
fileSystemRights == FileSystemRights.ReadAndExecute ||
fileSystemRights == FileSystemRights.ReadData ||
fileSystemRights == FileSystemRights.ListDirectory)
{
hasAccess = true;
}
}
}
return hasAccess;
}

How to check the 'Advanced Share' permissions on a folder using C#?

Hi I want to check if a particular folder is shared with a user.
for the normal share rights, I can the info by
DirectoryInfo di = new DirectoryInfo(path);
DirectorySecurity acl = di.GetAccessControl(AccessControlSections.All);
AuthorizationRuleCollection rules = acl.GetAccessRules(true, true, typeof(NTAccount));
//Go through the rules returned from the DirectorySecurity
foreach (AuthorizationRule rule in rules)
{
//If we find one that matches the identity we are looking for
if (rule.IdentityReference.Value.Equals(NtAccountName, StringComparison.CurrentCultureIgnoreCase))
{
//Cast to a FileSystemAccessRule to check for access rights
if ((((FileSystemAccessRule)rule).FileSystemRights & FileSystemRights.WriteData) > 0)
{
Console.WriteLine(string.Format("{0} has write access to {1}", NtAccountName, path));
}
else
{
Console.WriteLine(string.Format("{0} does not have write access to {1}", NtAccountName, path));
}
}
}
But the problem with this approach is that the if shared the folder using the "Advanced Share" option, as shown in image, it doesn't show any entry into the log.
How to calculate it?

C# - Modify File Permission ASP.NET MVC

I want modify the file's permission, and I am talking about permission like 666 / 777 etc.
In other words how tio change the permission of file from ANY to 666.
The goal is changing the permission of uploaded file on my ASP.NET MVC Web App.
public string Uploadfile(HttpRequestBase currentRequest)
{
string fileName = "";
for (int i = 0; i < currentRequest.Files.Count; i++)
{
if (currentRequest.Files[i].ContentLength > 0)
{
string strFileName = Guid.NewGuid().ToString() +
Path.GetExtension(currentRequest.Files[i].FileName);
currentRequest.Files[i].SaveAs(HttpContext.Current.Server.MapPath("/Upload/Task/" + strFileName));
fileName = strFileName;
}
}
return fileName;
}
}
You should look at File.SetAccessControl Method
public static void SetAccessControl(
string path,
FileSecurity fileSecurity
)
For example this is how you get the FileSecurity's of a file
FileSecurity fSecurity = File.GetAccessControl(filePath);
Then you create a FileSystemAccessRule
FileSystemAccessRule rule = new FileSystemAccessRule(SPECIFIC_USER, FileSystemRights.FullControl, AccessControlType.Allow);
And you add this Rule to the file's FileSecurity
File.SetAccessControl(filePath, fSecurity);
List of FileSystemRights possible values
http://msdn.microsoft.com/en-us/library/system.security.accesscontrol.filesystemrights(v=vs.110).aspx
Windows file security works differently to Unix, and there is no direct equivalent to chmod 666.
The method you're looking for is File.SetAccessControl, which takes the path to the file, and a FileSecurity object. The closest equivalent to '666' is probably to assign read/write permissions to the 'Everyone' user account.
To do this, you would use File.GetAccessControl to retrieve the current permissions for the file, add in the new read/write permissions to the FileSecurity object you just retrieved, and then use SetAccessControl to write the new permissions.
More information is available on MSDN here: http://msdn.microsoft.com/en-us/library/system.io.file.setaccesscontrol%28v=vs.110%29.aspx

How do I check folders for write-protection?

I'm a newbie to programming, and have only been working with standard console programs written with C#.
I am currently on an internship, and I've been asked to design a little Tool for them.
To be fair, the assignment is way over my ahead, and nothing like what I have previously made with C#.
The Tool basicly has to do the following:
User choses a folder to be searched.
Program checks all files in the folder, and all sub folders, and
checks the Write-protection if not already checked.
Program sets read-only attribute on all files, if there is not currently.
If this is not the place to search for help, please disregard my question.
Thanks for reading.
This is pretty much a copy paste from this thread:
The complete code should look something like:
public void SetAllFilesAsReadOnly(string rootPath)
{
//this will go over all files in the directory and sub directories
foreach (string file in Directory.EnumerateFiles(rootPath, "*.*", SearchOption.AllDirectories))
{
//Getting an object that holds some information about the current file
FileAttributes attr = File.GetAttributes(file);
// set the file as read-only
attr = attr | FileAttributes.ReadOnly;
File.SetAttributes(file,attr);
}
}
Following your comments, Just for better understanding, let's break it into bits and pieces:
once you have the file path, create the file attribute object:
var attr = File.GetAttributes(path);
For the following, you might want to read a bit about enum flags and bitwise
this is how you set as Read only:
// set read-only
attr = attr | FileAttributes.ReadOnly;
File.SetAttributes(path, attr);
this is how you un-set as Read only:
// unset read-only
attr = attr & ~FileAttributes.ReadOnly;
File.SetAttributes(path, attr);
And for getting all files you can use:
foreach (string file in Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories))
{
Console.WriteLine(file);
}
You can check it via
FileAttributes attr = File.GetAttributes(path);
if(attr.HasFlag( FileAttributes.ReadOnly ))
{
//it is readonly
}
This MSDN thread introduces the following code sample for acquiring folder permissions:
DirectorySecurity dSecurity = Directory.GetAccessControl(#"d:\myfolder");
foreach (FileSystemAccessRule rule in dSecurity.GetAccessRules(true, true, typeof(NTAccount)))
{
if (rule.FileSystemRights == FileSystemRights.Read)
{
Console.WriteLine("Account:{0}", rule.IdentityReference.Value);
}
}
Check out DirectoryInfo. In particular the Attributes property.

Categories