在我的 .NET 2.0 应用程序中,我需要检查是否存在足够的权限来创建文件并将其写入目录。为此,我有以下函数尝试创建一个文件并向其中写入一个字节,然后删除自身以测试权限是否存在。
我认为最好的检查方法是实际尝试去做,捕捉发生的任何异常。不过,我对一般的异常捕获并不是特别满意,那么有没有更好或者更容易接受的方法呢?
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;
        }
    }