74

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. I'm not particularly happy about the general Exception catch though, so is there a better or perhaps a more accepted way of doing this?

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;
        }
    }


  • Thanks for the code, though one thing, the caller may get the false impression that write permission is missing if the user is able to write but not able to delete. I would change this to use FileMode.Create and get rid of the file deletion. Obviously you won't need this code anymore, but I write this for the benefit of future readers. - n00b
  • string fullPath = directory + TEMP_FILE; Please use Path.Combine method instead of concatenating strings to get fullPath. Path.Combine(directory, TEMP_FILE) - nomail
  • What if someone punches in and then punches out the next day. What if they punch in and then punch out two days later? I'm sure people aren't supposed to do those things, but the behavior should be defined. - Scott Hannen

Linked


Related

Latest