如何使用c#将文件的所有者名称写入文件?

时间:2014-12-08 17:44:59

标签: c#

以下是如何获取文件所有者名称的代码:

using System.Security.AccessControl;
using System.Security.Principal;
using System.IO;

//...

FileInfo fileInfo = new FileInfo(@"1.txt");
FileSecurity fileSecurity = fileInfo.GetAccessControl();
IdentityReference identityReference = fileSecurity.GetOwner(typeof(NTAccount));
MessageBox.Show(identityReference.Value);

是否可以使用c#?

将此数据写入文件

1 个答案:

答案 0 :(得分:0)

从此question

File.Copy(@"1.txt", @"2.txt", true);
string userName = System.IO.File.GetAccessControl(@"1.txt").GetOwner(typeof(System.Security.Principal.NTAccount)).ToString();
var fs = File.GetAccessControl(@"2.txt");
var ntAccount = new NTAccount("DOMAIN", userName);
fs.SetOWner(ntAccount);

try {
   File.SetAccessControl(@"2.txt", 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;
}