复制一个文件并保留其原本的权限

9
使用File.Copy()方法时,文件会被复制到新目录,但是它将失去原来的权限。是否有一种方法可以复制文件而不丢失权限?

3
这个文件没有继承父文件夹的权限,对吗? - Lloyd Powell
1
如果我使用File.Copy(),则不会将任何权限应用于新文件。使用Alex的解决方案可以解决这个问题。 - WeaslB
2个回答

18

我认为你可以像这样做:

const string sourcePath = @"c:\test.txt";
const string destinationPath = @"c:\test2.txt"

File.Copy(sourcePath, destinationPath);

FileInfo sourceFileInfo = new FileInfo(sourcePath);
FileInfo destinationFileInfo = new FileInfo(destinationPath);

FileSecurity sourceFileSecurity = sourceFileInfo.GetAccessControl();
sourceFileSecurity.SetAccessRuleProtection(true, true);
destinationFileInfo.SetAccessControl(sourceFileSecurity);

GetAccessControl仅支持Windows操作系统。 - Sean
已经证明在.NET6中可以工作(因此很可能也适用于.NET Core)。 - Bohdan

-1

Alex的回答,已更新为.NET Core 3.1(实际上大多数.NET也可以):

var sourceFileInfo = new FileInfo(sourcePath);
var destinationFileInfo = new FileInfo(destinationPath);
// Copy the file
sourceFileInfo.CopyTo(destinationPath, true); // allow overwrite of the destination
// Update the file attributes
destinationFileInfo.Attributes = sourceFileInfo.Attributes


不适用于访问权限。 - Bohdan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接