9

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?

WeaslB
  • 123
  • 1
  • 4
  • 3
    The file isn't inheriting the parents folders permissions is it? – Lloyd Powell Feb 06 '12 at 16:54
  • 1
    If I use File.Copy() none of the permissions is applied to the new file. Using [Alex's solution](http://stackoverflow.com/a/9164000/1192774) works. – WeaslB Feb 06 '12 at 18:23

2 Answers2

18

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);
Matt Sullivan
  • 37
  • 1
  • 7
Alex Mendez
  • 5,120
  • 1
  • 25
  • 23
-1

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

Thomas O'Dell
  • 504
  • 6
  • 11