确定如果一个文件有写在.NET访问 [英] Determining if a file has write access in .NET

查看:121
本文介绍了确定如果一个文件有写在.NET访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个软件产品,这就像Apache的mod_rewrite的,但对于.NET。其中一项要求是支持RewriteLog命令,设置日志记录的路径。这工作得很好,但是最大的问题,我运行的是,用户设置的IIS用户没有访问路径。

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.

我已经想通了,我可以尝试写一个文件到硬盘进行测试。但这似乎哈克,我想找到一个这样做的非哈克的方式?任何人都知道一些API的,我可以称之为是中等信托安全检查文件的权限进行写访问?

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?

推荐答案

听起来像你要找的是什么的 FileIOPermission的(以System.Security.Permissions)类,它可以让你检查,如果你有继续之前的权限......这么说,你还是检测到您的必须通过捕获异常的权限;和你实际的写入操作过程中还是应该期待一个例外的可能性。

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

这篇关于确定如果一个文件有写在.NET访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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