C# 测试用户是否对文件夹具有写权限 [英] C# Test if user has write access to a folder

查看:20
本文介绍了C# 测试用户是否对文件夹具有写权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在实际尝试之前测试用户是否可以写入文件夹.

I need to test if a user can write to a folder before actually attempting to do so.

我已经实现了以下方法(在 C# 2.0 中),该方法尝试使用 Directory.GetAccessControl() 方法.

I've implemented the following method (in C# 2.0) that attempts to retrieve the security permissions for the folder using Directory.GetAccessControl() method.

private bool hasWriteAccessToFolder(string folderPath)
{
    try
    {
        // Attempt to get a list of security permissions from the folder. 
        // This will raise an exception if the path is read only or do not have access to view the permissions. 
        System.Security.AccessControl.DirectorySecurity ds = Directory.GetAccessControl(folderPath);
        return true;
    }
    catch (UnauthorizedAccessException)
    {
        return false;
    }
}

当我在谷歌上搜索如何测试写访问权限时,没有出现这样的情况,而且在 Windows 中实际测试权限似乎非常复杂.我担心我过度简化了事情,而且这种方法并不可靠,尽管它似乎确实有效.

When I was googling how to test for write access nothing like this came up and it appeared very complicated to actually test permissions in Windows. I am concerned that I am over-simplifying things and that this method is not robust, although it does seem to work.

我测试当前用户是否具有写访问权限的方法能正常工作吗?

Will my method to test if the current user has write access work correctly?

推荐答案

这是在 C# 中检查文件夹访问的完全有效的方法.它可能会失败的唯一地方是,如果您需要在一个紧密循环中调用它,其中异常的开销可能是一个问题.

That's a perfectly valid way to check for folder access in C#. The only place it might fall down is if you need to call this in a tight loop where the overhead of an exception may be an issue.

还有其他类似的 之前问过的问题.

这篇关于C# 测试用户是否对文件夹具有写权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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