FileSecurity not being set

488 Views Asked by At

For a seperate project my code reads in a file, destroys the old one and builds the new one etc. However i need to get the FileSecurity AccessControl from the old file and apply it to the new one. I'm fairly new to C# so i haven't worked with FileSecurity before, below is what i came up with, it doesn't error but it doesn't appear to work either.

public static void Main()
{
    try
    {
        string fileName = "test.txt";
        FileInfo fi = new FileInfo(fileName);
        FileSecurity fs = fi.GetAccessControl();

        Console.WriteLine("Got perms");
        Console.Read();

        Console.WriteLine("Adding access control to " + fileName);

        fi.SetAccessControl(fs);

        Console.WriteLine("Done.");
    }
    catch (Exception e)
    {
        Console.WriteLine(e);
    }
    Console.Read();
}

What i'd do to test is set the users to have full control over the file. Run the program to the first half, delete the file and create it again without full control then let the program finish. However when i go to the security tab of the file it doesn't show full control. I also tried creating a new FileInfo object after deleting the old file, but that didn't work either.

Any suggestions would be most helpful

1

There are 1 best solutions below

0
On

Something like this should work

        string dir = Path.GetDirectoryName(tbFileLocation.Text);

        DirectoryInfo di = new DirectoryInfo(dir);

        DirectorySecurity ds = di.GetAccessControl();

        FileSystemRights fsRights = FileSystemRights.FullControl;
        FileSystemAccessRule accessRule = new FileSystemAccessRule("Dummy", fsRights, AccessControlType.Allow);

        ds.AddAccessRule(accessRule);

        di.SetAccessControl(ds);