Dale Preston's Web Log
  
Friday, July 10, 2009
 

Setting file ACLs in .Net


I've been working on updating my ID3EmbedPictures app to fix a couple bugs. As part of the effort, I want to include functionality to set the file permissions on the album art in my Windows Media Player library to prevent Media Player from destroying it as it is wont to do.

I had a hard time finding how to set file permissions in .Net and especially how to remove inherited permissions. Here's a sample console app demonstrating the solution I finally used (after a little help from a Microsoft forum at http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/f3dd9496-794d-4f22-aa80-110fd2986e36. The code and the forum thread should tell the story.



class Program
{
static void Main(string[] args)
{
SetWorkingACL(@"E:\TestMusic - Copy\The Monkees\I'm A Believer And Other Hits\Folder.jpg");
}

private static void SetWorkingACL(string folderImage)
{
// Get the security information for the file.
FileSecurity fs = File.GetAccessControl(folderImage);

// Remove the inherited permissions.
fs.SetAccessRuleProtection(true, false);

// Get a collection of existing permissions.
AuthorizationRuleCollection rules = fs.GetAccessRules(true, true, typeof(NTAccount));

// Loop through and delete all explicit permissions.
// The loop processes explicit and inherited permissions but
// the RemoveAccessRule method won't remove
// the inherited permissions - which were removed
// above by SetAccessRuleProtection anyway.
foreach (AuthorizationRule rule in rules)
{
if (rule is AccessRule)
{
fs.RemoveAccessRule((FileSystemAccessRule)rule);
}
}

// Now add the two permissions I want.
fs.AddAccessRule(new FileSystemAccessRule(@"ServerAdmin", FileSystemRights.FullControl, AccessControlType.Allow));
fs.AddAccessRule(new FileSystemAccessRule(@"Users", FileSystemRights.ReadAndExecute, AccessControlType.Allow));

// Commit the changes to the file.
File.SetAccessControl(folderImage, fs);
}
}



Comments: Post a Comment

<< Home

Powered by Blogger