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

2

8

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?

Ruscio answered 7/2, 2014 at 9:0 Comment(0)
S
2

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.

Seyler answered 7/2, 2014 at 20:45 Comment(0)
D
2

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.

Deadhead answered 8/2, 2014 at 14:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.