I\'m trying to overcome the following situation.
Given a directory stored on an NTFS volume, where:
You need to take ownership before you add access.
using (var user = WindowsIdentity.GetCurrent())
{
var ownerSecurity = new FileSecurity();
ownerSecurity.SetOwner(user.User);
File.SetAccessControl("c:\\path\\to\\broken", ownerSecurity);
var accessSecurity = new FileSecurity();
accessSecurity.AddAccessRule(new FileSystemAccessRule(user.User, FileSystemRights.FullControl, AccessControlType.Allow));
File.SetAccessControl("c:\\path\\to\\broken", accessSecurity);
}
Also if you are setting DirectorySecurity you will need this
using (var user = WindowsIdentity.GetCurrent())
{
var ownerSecurity = new DirectorySecurity();
ownerSecurity.SetOwner(user.User);
Directory.SetAccessControl("c:\\path\\to\\broken", ownerSecurity);
var accessSecurity = new DirectorySecurity();
accessSecurity.AddAccessRule(new FileSystemAccessRule(user.User, FileSystemRights.FullControl, AccessControlType.Allow));
Directory.SetAccessControl("c:\\path\\to\\broken", accessSecurity);
}
If that doesn't work try this
http://blog.mikeobrien.net/2009/11/taking-ownership-and-setting-admin.html
I had the same problem and just posting here for anybody else who may come here searching like me:
You need to explicitly enable SeTakeOwnershipPrivilege in code. I found Process Privileges to be really helpful dealing with this sort of thing.
Here is how it fixed my code (seems like for some reason even though i have the privilege, the process doesn't unless i explicitly enable it):
using (new ProcessPrivileges.PrivilegeEnabler(Process.GetCurrentProcess(), Privilege.TakeOwnership))
{
directoryInfo = new DirectoryInfo(path);
directorySecurity = directoryInfo.GetAccessControl();
directorySecurity.SetOwner(WindowsIdentity.GetCurrent().User);
Directory.SetAccessControl(path, directorySecurity);
}
PS: Thanks Simon.. your answer gave me a place to start from.