WeaslB
WeaslB

Reputation: 123

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.

Is there a way to copy a file so that it doesn't lose the permissions?

Upvotes: 9

Views: 7031

Answers (2)

Thomas O'Dell
Thomas O'Dell

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

Alex Mendez
Alex Mendez

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

Related Questions