在我的.NET 2.0应用程序中,我需要检查是否有足够的权限来创建和写入文件到一个目录。为此,我有以下函数试图创建一个文件并写入一个字节,然后删除它自己以测试权限是否存在。
我认为最好的方法是实际尝试并捕获任何出现的异常来进行检查。但是,我对于使用一般的Exception catch并不是特别满意,那么有没有更好或更常见的做法呢?
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;
}
}
string fullPath = directory + TEMP_FILE;
Please use Path.Combine method instead of concatenating strings to get fullPath.Path.Combine(directory, TEMP_FILE)
- nomail