私の .NET 2.0 アプリケーションでは、ディレクトリにファイルを作成して書き込むための十分なアクセス許可が存在するかどうかを確認する必要があります。この目的のために、ファイルを作成して 1 バイトを書き込み、後でそれ自体を削除して、アクセス許可が存在することをテストする次の関数があります。
チェックする最善の方法は、実際に試して実行し、発生した例外をキャッチすることだと考えました。ただし、一般的な例外キャッチについては特に満足していません。これを行うためのより良い、またはおそらくより受け入れられている方法はありますか?
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;
}
}