1 |
using System;
|
2 |
using System.Collections.Generic;
|
3 |
using System.Linq;
|
4 |
using System.Text;
|
5 |
using System.IO;
|
6 |
using System.Security.AccessControl;
|
7 |
using System.Security.Principal;
|
8 |
|
9 |
namespace ChangeFileOwner
|
10 |
{
|
11 |
class ChangeFileOwner
|
12 |
{
|
13 |
static void Main(string[] args)
|
14 |
{
|
15 |
if (args.Length != 1)
|
16 |
{
|
17 |
Console.WriteLine("Usage: changefileowner.exe <filename>");
|
18 |
Environment.Exit(1);
|
19 |
}
|
20 |
string filename = args[0];
|
21 |
|
22 |
if ( !File.Exists(filename) )
|
23 |
{
|
24 |
Console.WriteLine("File not found: " + filename);
|
25 |
Environment.Exit(2);
|
26 |
}
|
27 |
|
28 |
FileSecurity acl = File.GetAccessControl(filename);
|
29 |
IdentityReference owner = acl.GetOwner(typeof(NTAccount));
|
30 |
Console.WriteLine(owner); // SID
|
31 |
|
32 |
//step 2
|
33 |
NTAccount ntAccount = new NTAccount("DAO", "Administrator");
|
34 |
acl.SetOwner(ntAccount);
|
35 |
|
36 |
FileSystemAccessRule facls = new FileSystemAccessRule(owner, FileSystemRights.Read, AccessControlType.Allow);
|
37 |
acl.RemoveAccessRuleAll(facls);
|
38 |
|
39 |
|
40 |
try
|
41 |
{
|
42 |
File.SetAccessControl(filename, acl);
|
43 |
}
|
44 |
catch (InvalidOperationException ex)
|
45 |
{
|
46 |
Console.WriteLine("You cannot assign ownership to that user." +
|
47 |
"Either you don't have TakeOwnership permissions, or it is not your user account."
|
48 |
);
|
49 |
throw;
|
50 |
}
|
51 |
}
|
52 |
}
|
53 |
}
|