简体   繁体   English

复制具有原始权限的文件

[英]Copy a file with its original permissions

When using the File.Copy() method the file is copied to its new directory however it loses its original permissions.当使用 File.Copy() 方法时,文件被复制到它的新目录,但是它失去了它原来的权限。

Is there a way to copy a file so that it doesn't lose the permissions?有没有办法复制文件以使其不会丢失权限?

I believe you can do something like this: 我相信你可以这样做:

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's answer, updated for .NET Core 3.1 (actually most .NET): 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM