Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append and write access to a Directory — FileIOPermission give not good result?

I have one issue which is in fact solved, but I totally do not understand why it behaves like this.

So I have a network share and I would like simply to verify if I have access to create new files and directories in that share. I have used two approaches to solve that, but in both I get different result. My test case is that I can't create files and directories on that share:

Trying to create a new Directory — not a nice way

try
{
    var testPath = Path.Combine(path, testDirectory)
    Directory.CreateDirectory(testPath)
}
catch
{
    // No access
}

This is a way which I do not like at all, but it works... I have an exception here, so it says correctly that I do not have the permission on specific path.

Using FileIOPermission — nicer way

try
{
    var writePermission = new FileIOPermission(FileIOPermissionAccess.Write, path)
    var appendPermission = new FileIOPermission(FileIOPermissionAccess.Append, path)
    writePermission.Demand()
    appendPermission.Demand()
}
catch
{
    // No access
}

With that approach I do not have any exception so it says to me that I have the permission to create new files — which is actually not true.

Anyone knows what is wrong with the second approach?

like image 273
user2323704 Avatar asked Feb 07 '14 09:02

user2323704


2 Answers

FileIOPermission doesn't check the actual permission on a file/directory. It's more of a "if I didn't have to worry about ACLs, would I be able to access this?" check.

Look at this post to see what FileIOPermission is really doing under the covers.

Then, look at this post to see how to interrogate the actual file system ACLs to see whether you can read/write a file.

like image 183
Nathan R Avatar answered Sep 27 '22 23:09

Nathan R


There is no safe alternative to doing file system operations than to try to do what you want and handle the exception(s) you are expecting such as the UnauthorizedAccessException if you want simple, easy to maintain and understandable code.

By explicitly handling UnauthorizedAccessException and ignoring the rest you can do your fallback logic for when that happen and the exception will bubble up and possibly be unhanded causing the application to stop (Your example 1). Your example 2 seems to break the .NET run-time contact on how to deal with run-time errors.

.NET and the managed run-time expect that you use and handle exceptions accordingly. See http://msdn.microsoft.com/en-us/library/8ey5ey87%28v=vs.91%29.aspx

I hope this helps you out somewhat at lest.

like image 39
grenangen Avatar answered Sep 28 '22 00:09

grenangen