【发布时间】:2010-11-19 21:04:30
【问题描述】:
在我的 .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;
}
}
【问题讨论】:
-
感谢您的代码,尽管有一点,如果用户能够写入但不能删除,调用者可能会误以为缺少写入权限。我会将其更改为使用 FileMode.Create 并摆脱文件删除。显然您将不再需要此代码,但我编写此代码是为了让未来的读者受益。
-
string fullPath = directory + TEMP_FILE;请使用 Path.Combine 方法而不是连接字符串来获取 fullPath。Path.Combine(directory, TEMP_FILE) -
如果有人打卡然后第二天打卡怎么办。如果他们打卡然后两天后打卡怎么办?我确信人们不应该做这些事情,但应该定义行为。
标签: c# .net winforms directory file-permissions