在我的.NET2.0应用程序中,我需要判断是否存在足够的权限来创建文件并将其写入目录.为此,我有以下函数,它try 创建文件并向其中写入单字节,然后删除自身以测试权限是否存在.

我认为判断的最好方法是实际try 并执行,捕获发生的任何异常.不过,我对一般的异常捕获并不是特别满意,所以有没有更好的或者更容易接受的方法来实现这一点呢?

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

推荐答案

RichardJason的答案在某种程度上是正确的.但是,对于运行代码的用户标识,您应该做的是computing the effective permissions.例如,上面的示例都不能正确说明组成员身份.

我很确定Keith Brown在他的wiki version(此时离线)The .NET Developers Guide to Windows Security中有一些代码可以做到这一点.这一点在他的Programming Windows Security本书中也有详细讨论.

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

.net相关问答推荐

为什么$NULL在ForEach-Object{}和Foreach()中的行为不同?

升级到.NET8后,SignalR(在坞站容器上)网关损坏

更改列表中的值

CustomControl 计算自己的宽度和高度 - 使用 bounds.Height=0 调用 ArrangeOverride

为什么 GetShortestDayName 返回的名称比预期的短?

如何在 C# 中自动删除临时文件?

如何为多种文件类型设置 FileSystemWatcher 过滤器?

StreamWriter.Flush() 和 StreamWriter.Close() 有什么区别?

调整小数精度,.net

extern 在 C# 中是如何工作的?

.NET 4.0 中有内置的二叉搜索树吗?

使用 C# 在 .NET 4.0 中 Task.Run 的替代方法是什么?

HashSet 是否保留插入顺序?

是否可以更改 Winforms 组合框以禁用输入?

如何更改 double.ToString() 中小数点的符号?

寻找 .NET 的命令行参数解析器

使 HashSet 不区分大小写

如何在不使用 3rd 方库的情况下登录 C#?

.NET 中的 java.lang.IllegalStateException?

C# ListView 列宽自动