I would like to apply a folder's Security Settings to all descendants in C#. Essentially, I would like to do the same thing as 'Replace all existing inheritable permissions on all descendants with inheritable permissions from this object' within 'Advanced Security Settings for [Folder]'.
Are there any elegant ways to approach this?
After some quality time with google and MSDN I came up with the following bit of code. Seems to work just fine.
static void Main(string[] args)
{
DirectoryInfo dInfo = new DirectoryInfo(#"C:\Test\Folder");
DirectorySecurity dSecurity = dInfo.GetAccessControl();
ReplaceAllDescendantPermissionsFromObject(dInfo, dSecurity);
}
static void ReplaceAllDescendantPermissionsFromObject(
DirectoryInfo dInfo, DirectorySecurity dSecurity)
{
// Copy the DirectorySecurity to the current directory
dInfo.SetAccessControl(dSecurity);
foreach (FileInfo fi in dInfo.GetFiles())
{
// Get the file's FileSecurity
var ac = fi.GetAccessControl();
// inherit from the directory
ac.SetAccessRuleProtection(false, false);
// apply change
fi.SetAccessControl(ac);
}
// Recurse into Directories
dInfo.GetDirectories().ToList()
.ForEach(d => ReplaceAllDescendantPermissionsFromObject(d, dSecurity));
}
You may find the DirectorySecurity class to be useful for this.
http://msdn.microsoft.com/en-us/library/system.security.accesscontrol.directorysecurity.aspx
There may be some other valuable tools within the System.Security.AccessControl
namespace
Related
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);
}
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
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.
Hy,
is there any posibillities to restrict acces to a folder stored on an sd card?
I tried this but it doesn't work...Any ideas are welcome.
Thanks...
public static void setRight(string dirName,string account, FileSystemRights rights, AccessControlType controlType)
{
DirectoryInfo dir = new DirectoryInfo(dirName);
DirectorySecurity dSecurity = new DirectorySecurity();// Directory.GetAccessControl(dirName);
// Add the FileSystemAccessRule to the security settings.
dSecurity.AddAccessRule(new FileSystemAccessRule(account, rights, controlType));
// Set the new access settings.
dir.SetAccessControl(dSecurity);
Directory.SetAccessControl(dirName, dSecurity);
}
Try using the File.Encrypt and File.Decrypt methods. You can use recursion to encrypt directories, by encrypting all files in them.
I am Trying to write a Functionality where i could get the Complete List of All File Name in all Drives,but I am stuck in a place where its giving me security exception to read all files.
I went through many of the articles in this site and the other, but unable to figure out how to set complete access rights
this post was much useful but i am getting an Exception which was unanswered in that thread
How to grant read access to all files in a folder and subfolders using c#?
Now My code looks like this
[FileIOPermission(SecurityAction.LinkDemand, Read = "C:\\")]
public void GetAllFilesFromPhysicalDrives()
{
List<DriveInfo> allphydrives = GetListofPhysicalDrivesOnly(); //Gets All Physical DrivesCollection
try
{
foreach (DriveInfo dr in allphydrives)
{
DirectoryInfo dir = new DirectoryInfo(dr.Name);
DirectorySecurity dirSecurity = dir.GetAccessControl();
dirSecurity.AddAccessRule(new FileSystemAccessRule(Environment.UserName, FileSystemRights.Read, AccessControlType.Allow));
dir.SetAccessControl(dirSecurity);
FileSystemAccessRule faRule;
FileSystemRights fsrRights;
DirectorySecurity dirsec;
fsrRights = FileSystemRights.FullControl;
faRule = new FileSystemAccessRule(new System.Security.Principal.NTAccount("my-pc\\me"),fsrRights,InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit,PropagationFlags.InheritOnly, AccessControlType.Allow);
System.Security.Principal.NTAccount account = new System.Security.Principal.NTAccount("me\\me");
dirsec = Directory.GetAccessControl("C:\\");
dirsec.SetOwner(account);
dirsec.AddAccessRule(faRule);
Directory.SetAccessControl("C:\\", dirsec);
}
}
catch(Exception ex)
{
}
}
so when the code to set the access executes i am getting an "Attempt to Perform UnAuthorized Operation" Exception
I don't want to set Permission for files one by one because its a tedious task so help me which would happen dynamically via code for All folders so that i could iterate and get all file names .(I don't intend to get windows related files or kernal files ,just the user created files is enough)