8

当使用 File.Copy() 方法时,文件被复制到它的新目录,但是它失去了原来的权限。

有没有办法复制文件以免丢失权限?

4

2 回答 2

15

我相信你可以做这样的事情:

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);
于 2012-02-06T17:01:49.767 回答
0

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

于 2021-08-19T06:14:18.923 回答