File.Move不会从目标目录继承权限?

Jos*_*gry 22 c# file-permissions .net-4.0 windows-7

如果在创建文件时出现问题,我一直在写一个临时文件,然后移动到目的地.就像是:

        var destination = @"C:\foo\bar.txt";
        var tempFile = Path.GetTempFileName();
        using (var stream = File.OpenWrite(tempFile))
        {
            // write to file here here
        }

        string backupFile = null;
        try
        {
            var dir = Path.GetDirectoryName(destination);
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
                Util.SetPermissions(dir);
            }

            if (File.Exists(destination))
            {
                backupFile = Path.Combine(Path.GetTempPath(), new Guid().ToString());
                File.Move(destination, backupFile);
            }

            File.Move(tempFile, destination);

            if (backupFile != null)
            {
                File.Delete(backupFile);
            }
        }
        catch(IOException)
        {
            if(backupFile != null && !File.Exists(destination) && File.Exists(backupFile))
            {
                File.Move(backupFile, destination);
            }
        }
Run Code Online (Sandbox Code Playgroud)

问题是在这种情况下新的"bar.txt"不会从"C:\ foo"目录继承权限.然而,如果我直接在"C:\ foo"中通过explorer/notepad等创建文件,则没有问题,所以我相信权限在"C:\ foo"上正确设置.

更新

找到移动文件夹时,不会自动更新继承的权限,也可能适用于文件.现在正在寻找一种强制更新文件权限的方法.这样做有更好的方法吗?

Jos*_*gry 32

发现我需要的是这个:

var fs = File.GetAccessControl(destination);
fs.SetAccessRuleProtection(false, false);
File.SetAccessControl(destination, fs);
Run Code Online (Sandbox Code Playgroud)

这会重置文件权限以继承.

  • 文件移动后你必须这样做吗?在这种情况下,它不再是原子的 - 在权限到位之前,有人可能会尝试读取文件 (3认同)
  • @JosephKingry.谢谢,这帮助了我.但是,我还希望移除任何显式权限.再多几行代码.http://stackoverflow.com/a/12821819/486660 (3认同)