简体   繁体   中英

C# save directory permissions

I've been trying to find a way to store permissions on a directory. I am currently using SetACL to help. If I could change ownership on directories/registry without it that would be preferred, but that's a different story. An example is this:

Check current owner and permissions for that owner. Change to permissions and owner on button click > change it back to the original when another button is clicked.

To save the question of why, my team does technical support. We remote into a computer, perform our t/s and leave. We need to be able to change permissions then revert it back the way it was.

Any help is appreciated.

If you use the System.Management and System.Management.Instrumentation namespaces, you can use the Directory.GetAccessControl method to get who has access to a folder. You can then use the AddAccessRule and SetAccessControl methods to actually apply your new permissions. When you are done, you could remove your new permissions. Here is an article that walks you through how to change permissions on a folder:

http://www.redmondpie.com/applying-permissions-on-any-windows-folder-using-c/

The basic code this author uses is as follows:

DirectoryInfo myDirectoryInfo = new DirectoryInfo(yourFolderHere);

// Get a DirectorySecurity object that represents the 
// current security settings.
DirectorySecurity myDirectorySecurity = myDirectoryInfo.GetAccessControl();

// Builds a new user string for who we want to give permissions to
string User = System.Environment.UserDomainName + "\\" + yourUserName; 

// Creates the permissions to apply 
myDirectorySecurity.AddAccessRule(new FileSystemAccessRule(User, 
                                  FileSystemRights.FullControl, AccessControlType.Allow));

// Set the new access settings. 
myDirectoryInfo.SetAccessControl(myDirectorySecurity);

// Showing a Success Message
MessageBox.Show("Permissions Altered Successfully");
}

As for setting the owner, here is a good SO article on how to do so:

C# - How to use DirectorySecurity.SetOwner() ? I'm having troubles

However, if you wanted to set the owner to be someone else (since I would assume you don't need to assign ownership permissions to a user when they already have access to assign ownership permissions), this above method won't work I don't believe. I have found documentation on how to set the owner to be someone other than yourself. Here is the link:

http://blog.salamandersoft.co.uk/index.php/2009/10/setting-the-owner-of-files-and-directories-in-c/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM