检查 .NET 中的目录和文件写入权限 [英] Checking for directory and file write permissions in .NET

查看:26
本文介绍了检查 .NET 中的目录和文件写入权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 .NET 2.0 应用程序中,我需要检查是否存在足够的权限来创建文件并将其写入目录.为此,我有以下函数尝试创建一个文件并向其中写入一个字节,然后删除自身以测试权限确实存在.

In my .NET 2.0 application, I need to check if sufficient permissions exist to create and write to files to a directory. To this end, I have the following function that attempts to create a file and write a single byte to it, deleting itself afterwards to test that permissions do exist.

我认为最好的检查方法是实际尝试并执行它,捕获发生的任何异常.不过,我对一般的异常捕获并不是特别满意,那么是否有更好或更可接受的方法来做到这一点?

I figured the best way to check was to actually try and do it, catching any exceptions that occur. I'm not particularly happy about the general Exception catch though, so is there a better or perhaps a more accepted way of doing this?

private const string TEMP_FILE = "\tempFile.tmp";

/// <summary>
/// Checks the ability to create and write to a file in the supplied directory.
/// </summary>
/// <param name="directory">String representing the directory path to check.</param>
/// <returns>True if successful; otherwise false.</returns>
private static bool CheckDirectoryAccess(string directory)
{
    bool success = false;
    string fullPath = directory + TEMP_FILE;

    if (Directory.Exists(directory))
    {
        try
        {
            using (FileStream fs = new FileStream(fullPath, FileMode.CreateNew, 
                                                            FileAccess.Write))
            {
                fs.WriteByte(0xff);
            }

            if (File.Exists(fullPath))
            {
                File.Delete(fullPath);
                success = true;
            }
        }
        catch (Exception)
        {
            success = false;
        }
    }

推荐答案

The answers by RichardJason 的方向是正确的.但是你应该做的是计算有效权限 用于运行您的代码的用户身份.例如,以上示例均未正确说明群组成员身份.

The answers by Richard and Jason are sort of in the right direction. However what you should be doing is computing the effective permissions for the user identity running your code. None of the examples above correctly account for group membership for example.

我很确定 Keith Brown 在他的 wiki 版本(目前离线)://alt.pluralsight.com/wiki/default.aspx/Keith.GuideBook.HomePage" rel="noreferrer">Windows 安全性的 .NET 开发人员指南.这也在他的Programming Windows Security一书中进行了合理的详细讨论.

I'm pretty sure Keith Brown had some code to do this in his wiki version (offline at this time) of The .NET Developers Guide to Windows Security. This is also discussed in reasonable detail in his Programming Windows Security book.

计算有效权限不适合胆小的人,您的代码尝试创建文件并捕获抛出的安全异常可能是阻力最小的路径.

Computing effective permissions is not for the faint hearted and your code to attempt creating a file and catching the security exception thrown is probably the path of least resistance.

这篇关于检查 .NET 中的目录和文件写入权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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