Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting / setting file owner in C#

Tags:

c#

.net

I have a requirement to read and display the owner of a file (for audit purposes), and potentially changing it as well (this is secondary requirement). Are there any nice C# wrappers?

After a quick google, I found only the WMI solution and a suggestion to PInvoke GetSecurityInfo

like image 959
Grzenio Avatar asked Sep 30 '08 13:09

Grzenio


People also ask

How do I find owner in Linux?

The best Linux command to find file owner is using “ls -l” command. Open the terminal then type ls -l filename in the prompt. The 3rd column is the file owner. The ls command should be available on any Linux system.

What is ownership of a file?

Initially, a file's owner is identified by the user ID of the person who created the file. The owner of a file determines who may read, write (modify), or execute the file. Ownership can be changed with the chown command.


1 Answers

No need to P/Invoke. System.IO.File.GetAccessControl will return a FileSecurity object, which has a GetOwner method.

Edit: Reading the owner is pretty simple, though it's a bit of a cumbersome API:

const string FILE = @"C:\test.txt";  var fs = File.GetAccessControl(FILE);  var sid = fs.GetOwner(typeof(SecurityIdentifier)); Console.WriteLine(sid); // SID  var ntAccount = sid.Translate(typeof(NTAccount)); Console.WriteLine(ntAccount); // DOMAIN\username 

Setting the owner requires a call to SetAccessControl to save the changes. Also, you're still bound by the Windows rules of ownership - you can't assign ownership to another account. You can give take ownership perms, and they have to take ownership.

var ntAccount = new NTAccount("DOMAIN", "username"); fs.SetOwner(ntAccount);  try {    File.SetAccessControl(FILE, fs); } catch (InvalidOperationException ex) {    Console.WriteLine("You cannot assign ownership to that user." +     "Either you don't have TakeOwnership permissions, or it is not your user account."    );    throw; } 
like image 181
Mark Brackett Avatar answered Oct 05 '22 00:10

Mark Brackett