Reputation: 123
When using the File.Copy() method the file is copied to its new directory however it loses its original permissions.
Is there a way to copy a file so that it doesn't lose the permissions?
Upvotes: 9
Views: 7031
Reputation: 554
Alex's answer, updated for .NET Core 3.1 (actually most .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
Upvotes: -1
Reputation: 5150
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);
Upvotes: 18