小编典典

在.NET中检查目录和文件的写入权限

c#

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

我认为检查的最佳方法是实际尝试并捕获发生的任何异常。不过,我对一般的Exception捕获并不特别满意,因此,有没有更好的方法,或者也许是一种更可接受的方法?

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

阅读 358

收藏
2020-05-19

共1个答案

小编典典

理查德杰森的答案都是正确的方向。但是,您应该做的是计算运行代码的用户身份的有效权限。例如,以上示例均未正确说明组成员身份。

我很确定Keith
Brown
在他的Windows安全.NET开发人员指南的Wiki版本中(此时处于脱机状态)有一些代码可以执行此操作。在他的《编程Windows安全性》一书中也对此进行了详细的讨论。

计算有效权限不适合胆怯的人,代码尝试创建文件并捕获引发的安全异常可能是阻力最小的途径。

2020-05-19