在我的.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;
}
}