views:

205

answers:

1

I have created a software product, that acts like the Apache mod_rewrite, but for .NET. One of the requirements is to support the RewriteLog command which sets a path for logging. This works fine, however the biggest issue I run in to is that users set a path that the IIS user doesn't have access to.

I would like to throw an exception to the user about the lack of write access, by checking the permissions of the path to make sure write access is available.

I have already figured out that I can trying write a file to the hard disk to test. But this seems hacky and I would like to find a non-hacky way of doing this? Anybody know of some API that I can call that is Medium-Trust safe to check the file permissions for write access?

+1  A: 

Sounds like what you're looking for is the FileIOPermission (in System.Security.Permissions) class, which lets you check if you have permissions before proceeding... that said, you still detect that you don't have permissions by catching an exception; and you should still expect the possibility of an exception during the actual write operation.

using System.Security.Permissions;
...
public void CheckForWriteRights(string path)
{
    FileIOPermission permission = new FileIOPermission(FileIOPermissionAccess.Write, path);
    try
    {
        permission.Demand();
        // the application does have Write rights to the path
    }
    catch
    {
        // the application doesn't have rights to the path
    }
}
STW
fyi: you should also take a look at the FileIOPermissionAttribute (and the permission and permissionattribute classes in general). There are two approaches to checking permissions, declarative and imperitive. For your specific example the declarative approach (using an attribute on the class) is typically not the better option, as it requires an absolute path to be compiled in--however the Permissions namespace is an important aspect of the .NET framework which you should be aware of and have at least a basic understanding of
STW
Thanks for the help, your initial solution is what i needed. I ended up going with a one line protection of: new FileIOPermission(FileIOPermissionAccess.Write, path).Demand(); With out the try/catch. But your solution led me to this answer
Nick Berardi