Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 628
WeaslB Avatar asked Feb 06 '12 16:02

WeaslB


People also ask

How do you copy and preserve permissions?

Preserve File Permissions Using cp The standard cp command has all you need to retain file permissions while copying. You can use the -p option of cp to preserve the mode, ownership, and timestamps of the file. However, you will need to add the -r option to this command when dealing with directories.

Can you copy a file with read permissions?

If you grant read permissions to a file, you also grant the permission to copy that file's contents to another medium. The only way to prevent the files in question from being copied is to deny read access to the files. You cannot have files be read only AND not copyable. Save this answer.

Does copy and paste keep permissions?

When moving files, Windows keeps the original file permissions if you are moving files to a location within the same volume. If you copy and paste or move a file to a different volume, it will be assigned the permissions of the destination folder. Microsoft has a fix for this situation. (This is a per-system fix.)


1 Answers

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);
like image 129
Alex Mendez Avatar answered Sep 19 '22 21:09

Alex Mendez