views:

392

answers:

3

Is there a way to change owner of saved file using IIS on Windows Server. The easier the better. It doesn't matter either this will have to be done during saving or changing file owner after file is already saved to disc. An example in ASP.NET is highly apriciated.

A: 

While this is not a customized example, I believe your answer lies in the System.Security.AccessControl namespace.

Take a look at the FileSecurity Class which lets you identify rules and permissions. The FileSecurity class is used by methods such as File.Create().

Vaibhav
+1  A: 

In theory it should be fairly straight forward. You should be able to do something like this to change the ownership of an existing file:

string domain = "domain";
string user = "username";

FileInfo info = new FileInfo(@"c:\test.txt");

FileSecurity security = info.GetAccessControl();

System.Security.Principal.NTAccount newOwner =
    new System.Security.Principal.NTAccount(domain, user);

security.AddAccessRule(
        new FileSystemAccessRule(newOwner, FileSystemRights.FullControl,
            AccessControlType.Allow));
security.SetAccessRuleProtection(true, false);
security.SetOwner(newOwner);

info.SetAccessControl(security);

In practice however this doesn't actually work because of a limitation that Windows imposes. Windows won't allow you to the change the owner of the file to anything other than the current user or the administrators group.

When it hits the last line you will get the exception "The security identifier is not allowed to be the owner of this object".

Googling suggests that it may be possible to work round this problem, but I have failed to get the work arounds to work when I have tried in the past. I'd be very interested to hear if anyone had successfully achieved the work around.

andynormancx
A: 

A user can assign ownership to other users if they have the Restore Files and Directories privilege. This is disabled by default so you need to enable it before trying to set the owner. .Net doesn't have built in support for this so you'll need to PInvoke AdjustTokenPrivileges and use other unmanaged functions to get the inputs to this.

I've written a detailed description of its use on my blog

Richard Willis