使用File.Copy()方法时,文件会被复制到新目录,但是它将失去原来的权限。是否有一种方法可以复制文件而不丢失权限?
我认为你可以像这样做:
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);
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