In my .NET 2.0 application, I need to check if sufficient permissions exist to create and write to files to a directory. To this end I have the following function that attempts to create a file and write a single byte to it, deleting itself afterwards to test that permissions do exist.
I figured the best way to check was to actually try and do it, catching any exceptions that occur, but I'm not particularly happy about the general Exception catch, so is there a better, or perhaps a more accepted way of doing this?
Any comments or suggestions welcome.
Thanks.
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
{
// Attempt to create a temporary file.
using (FileStream fs = new FileStream(fullPath, FileMode.CreateNew, FileAccess.Write))
{
fs.WriteByte(0xff);
}
// Delete temporary file if it was successfully created.
if (File.Exists(fullPath))
{
File.Delete(fullPath);
success = true;
}
}
catch (Exception)
{
success = false;
}
}