附加和写入目录访问权限-FileIOPermission效果不好吗? [英] Append and write access to a Directory — FileIOPermission give not good result?

查看:152
本文介绍了附加和写入目录访问权限-FileIOPermission效果不好吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实际上可以解决的问题,但是我完全不明白为什么它会这样表现.

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:

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.

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?

推荐答案

除了尝试执行所需的操作并处理期望的异常(如UnauthorizedAccessException)外,没有其他安全的选择可以进行文件系统操作.您想要简单,易于维护且易于理解的代码.

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.

通过显式处理UnauthorizedAccessException并忽略其余部分,您可以针对何时发生回退逻辑进行处理,并且异常将冒泡并有可能无法处理,从而导致应用程序停止(您的示例1).您的示例2似乎打破了有关如何处理运行时错误的.NET运行时联系.

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和托管运行时期望您相应地使用和处理异常.请参阅 http://msdn.microsoft.com/zh-cn/library/8ey5ey87%28v = vs.91%29.aspx

.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.

这篇关于附加和写入目录访问权限-FileIOPermission效果不好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆