File.Move does not inherit permissions from target directory?

Posted by Joseph Kingry on Stack Overflow See other posts from Stack Overflow or by Joseph Kingry
Published on 2010-05-28T14:36:30Z Indexed on 2010/05/28 17:02 UTC
Read the original article Hit count: 263

In case something goes wrong in creating a file, I've been writing to a temporary file and then moving to the destination. Something like:

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

The problem is that the new "bar.txt" in this case does not inherit permissions from the "C:\foo" directory. Yet if I create a file via explorer/notepad etc directly in the "C:\foo" there's no issues, so I believe the permissions are correctly set on "C:\foo".

Update

Found Inherited permissions are not automatically updated when you move folders, maybe it applies to folders as well. Now looking for a way to force an update of file permissions. Is there a better way overall of doing this?

© Stack Overflow or respective owner

Related posts about c#

Related posts about windows-7