【问题标题】:File.Move does not inherit permissions from target directory?File.Move 不从目标目录继承权限?
【发布时间】:2011-02-25 04:09:50
【问题描述】:

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

        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);
            }
        }

问题是在这种情况下新的“bar.txt”没有从“C:\foo”目录继承权限。但是,如果我通过资源管理器/记事本等直接在“C:\foo”中创建文件,则没有问题,所以我相信“C:\foo”上的权限设置正确。

更新

找到Inherited permissions are not automatically updated when you move folders,也许它也适用于文件。现在正在寻找一种强制更新文件权限的方法。有没有更好的方法来做到这一点?

【问题讨论】:

    标签: c# windows-7 .net-4.0 file-permissions


    【解决方案1】:

    发现我需要的是这样的:

    var fs = File.GetAccessControl(destination);
    fs.SetAccessRuleProtection(false, false);
    File.SetAccessControl(destination, fs);
    

    这会将文件权限重置为继承。

    【讨论】:

    • 文件已被移动后是否必须执行此操作?在这种情况下,它不再是原子的 - 有人可能会在权限到位之前尝试读取文件
    • @Neil 是的,这将是在移动之后,是的,它将使它不再是原子的。
    • @JosephKingry。谢谢,这帮助了我。但是,我还想删除移动导致的任何显式权限。只需多几行代码。 stackoverflow.com/a/12821819/486660
    • 复制文件时是否也需要这样做,或者在这种情况下是否会自动继承权限?
    猜你喜欢
    • 2010-12-04
    • 2013-07-18
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-29
    • 2015-03-26
    • 2017-07-03
    相关资源
    最近更新 更多