Determining if a file has write access in .NET

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?

Add Comment
1 Answer(s)

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
    }
}
Answered on July 2, 2016.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.