Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
663 views
in Technique[技术] by (71.8m points)

c# - Taking ownership of a file or folder

Before I pull out the rest of my hair I'd like to get some input on this.
I'm trying to take ownership of a folder. I'm running the program as administrator of course and I do have rights to take ownership since I can change the owner in explorer.

I can however change the owner if either administrator or my account owns it, and I can change permissions if I already have ownership.
If I try to give myself ownership of a file, lets say owned by SYSTEM, then I get an unauthorizedexception.

I've tried some different things with the accesscontrol methods but nothing works, this latest method I think is directly by the book.

        private static void makePerm(string file, NTAccount account)
    {
        FileInfo finfo = new FileInfo(file);
        FileSecurity fsecurity = finfo.GetAccessControl();
        //also tried it like this //fsecurity.ResetAccessRule(new FileSystemAccessRule(string.Format(@"{0}{1}", Environment.UserDomainName.ToString(), Environment.UserDomainName.ToString()), FileSystemRights.FullControl, AccessControlType.Allow));
        fsecurity.SetOwner(account);
        finfo.SetAccessControl(fsecurity);
    }

I'm trying this on Windows 7 btw.
What am I missing here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 as Luke mentions above. I found this Process Privileges to be really helpful dealing with this sort of thing.

Here is how it fixed my code:

using System;
using System.Diagnostics;

// ...
using (new ProcessPrivileges.PrivilegeEnabler(Process.GetCurrentProcess(), Privilege.TakeOwnership))
{
    directoryInfo = new DirectoryInfo(path);
    directorySecurity = directoryInfo.GetAccessControl();

    directorySecurity.SetOwner(WindowsIdentity.GetCurrent().User);
    Directory.SetAccessControl(path, directorySecurity);    
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...