C# • Deny “Self” Read Rights

Listing 2. This method loops through the access control entries that are associated with the file, and then displays the ACEs on the screen with the help of the custom ShowRightsForm dialog box.

private void DenyFileReadFromSelf(string filename)
{
	// create a new rule for "self"
	WindowsIdentity self =
		WindowsIdentity.GetCurrent();
	SecurityIdentifier selfSID = self.User;
	FileSystemAccessRule fsRule =
		new FileSystemAccessRule(selfSID,
		FileSystemRights.Read,
		AccessControlType.Deny);
	// modify the file's access control list
	FileSecurity fileSec =
		System.IO.File.GetAccessControl(filename);
	fileSec.AddAccessRule(fsRule);
	System.IO.File.SetAccessControl(
		filename,fileSec);
	MessageBox.Show(
		"New access control entries "+
		"have been set.", this.Text);
}