复制文件如何保留旧权限?

时间:2016-12-09 10:52:07

标签: c# permissions copy access-control accesscontrolexception

当复制文件更改新权限时,我希望通过“IREAuthenSharePath”复制文件。我想继续许可。

代码C#

IREAuthenSharePath pAuthen = new IREAuthenSharePath();
string shareNameConfirm = "Test\COPY_File";
string targetPath = pAuthen.LoginToShareMapDrive(serverName, shareNameConfirm, userName, password); // \\10.111.210.20\Test\COPY_File

foreach (GridViewRow row in gvDetail.Rows)
{
  var isChecked = (row.FindControl("cbxStatus") as CheckBox).Checked;
  if (!isChecked) continue;

  string fileName = (row.FindControl("lblName") as Label).Text; //Test01
  string filePath = (row.FindControl("lblHFPath") as Label).Text; // \\10.111.210.20\Test\Ori_File\Test01

  //Copy TAP File
  string sourcePath = @"\\10.111.210.20\Test\Ori_File";
  string sourceFile = Path.Combine(sourcePath, fileName);
  string destFile = Path.Combine(targetPath, fileName);
  File.Copy(sourceFile, destFile, true);
  FileInfo file1 = new FileInfo(filePath);
  FileInfo file2 = new FileInfo(filePath);
  FileSecurity ac1 = file1.GetAccessControl();
  ac1.SetAccessRuleProtection(true, true);
  file2.SetAccessControl(ac1); ==> Error Attempted to perform an unauthorized operation.
}

示例 复制文件之前

**File name      Permission**
TEST01         0666
TEST02         0062
TEST03         0444
TEST04         0777

复制文件后

File name      Permission
TEST01         0777
TEST02         0777
TEST03         0777
TEST04         0777

我希望复制的文件保留旧的权限,我不希望它拥有0777的权限。

1 个答案:

答案 0 :(得分:0)

你能检查一下这是否有帮助。 https://social.msdn.microsoft.com/Forums/en-US/99d3825a-748f-4bd8-a77e-6f4f3b12267b/how-to-give-access-file-full-control-by-c-code-?forum=csharplanguage

FileInfo fileInfo = new FileInfo("database_library.mdb");
        FileSecurity accessControl = fileInfo.GetAccessControl();
        accessControl.AddAccessRule(new FileSystemAccessRule("user account name", FileSystemRights.FullControl, AccessControlType.Allow));
        fileInfo.SetAccessControl(accessControl);