Pregunta

I'm going to set the full access permission to a file (fileName). I found a code sample:

var security = IO.File.GetAccessControl(fileName);

security.AddAccessRule(new Security.AccessControl.FileSystemAccessRule(
    new SecurityIdentifier(WellKnownSidType.WorldSid, null),
    Security.AccessControl.FileSystemRights.FullControl,
    Security.AccessControl.AccessControlType.Allow));

IO.File.SetAccessControl(fileName, security);

It is working well but I don't understand why should I pass the filename to the SetAccessControl method (I already provided it in the first line)? I made a change to the code and see this is working too:

var security = IO.File.GetAccessControl(anotherFileName);

security.AddAccessRule(new Security.AccessControl.FileSystemAccessRule(
    new SecurityIdentifier(WellKnownSidType.WorldSid, null),
    Security.AccessControl.FileSystemRights.FullControl,
    Security.AccessControl.AccessControlType.Allow));

IO.File.SetAccessControl(fileName, security);

So what is the use of anotherFileName here?

¿Fue útil?

Solución

GetAccessControl will get the FileSecurity.

From MSDN:

Represents the access control and audit security for a file. [...] This class represents access and audit rights as a set of rules.

A FileSecurity is not dependent on a particular file, so you can use one FileSecurity on multiple files to set identical access and audit rights.

This is why you need to specify the filename.

An alternative would be to use the FileInfo class.

var fileInfo = new FileInfo(filename);
var security = fileInfo.GetAccessControl();
// [...]
fileInfo.SetAccessControl(security);

The constructors from MSDN:

FileSecurity()

Will create an empty FileSecurity object.

FileSecurity(String, AccessControlSections)

Creates an empty FileSecurity object from the specified file using the specified values of the AccessControlSections enumeration.

Otros consejos

Security information (ACL) is not tied to object, so you can get current value for one file and apply to any other file.

This is exactly the same as string name = person.Name - name is not tied to a person, just some property of one.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top