FileSystemRightsHelper

The FileSystemRightsHelper class is a utility class to get the IO permission of a directory or a file.

DirectorySecurity security = System.IO.Directory.GetAccessControl(path);

AuthorizationRuleCollection rules = security.GetAccessRules(true, true, typeof(SecurityIdentifier));

FileSystemRightsHelper rights = new FileSystemRightsHelper(rules);

if (rights.CanWrite && rights.CanRead)
{
    Console.WriteLine("R/W access");
}
else
{
    if (rights.CanWrite)
	{
        Console.WriteLine("Only Write access");
    }  
	else if (rights.CanRead) 
	{
        Console.WriteLine("Only Read access");
    }
	else
	{
        Console.WriteLine("No Read and Write accesses");
    }
}

When I want to know “Do I have permission to Read or Write this file?”, I found this article by Bruce Hatt, “Testing File Access Rights in .NET 2.0“.

Thanks Bruce Hatt, I can get the answer of this common question.

Everything is OK, exception the code itself. I DO NOT LIKE THE CODE AT ALL!

So I rewrited my FileSystemRightsHelper (not just simple refactor).

Now it’s more effective and elegent.

Check it out!

FileSystemRightsHelper.cs

Tags: , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: