Click here to Skip to main content
15,895,084 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
I'm working on an application in Winforms, C #, VS, this application has to save a pdf in a folder selected, but first I validate when starting the app, If it can access this folder, otherwise not start the app and shows warning.

How can I validate my app has write access to a folder.

regards
Posted
Comments
Sergey Alexandrovich Kryukov 17-Mar-14 19:03pm    
Validate? Why?! :-)
—SA

As SA said, just try to create the file. Below is a simple routine that returns true if a file can be created in the specified directory.
C#
private bool CheckDirectoryWriteAccess(string dirPath)
{
    bool result = false;
    // check for directory access
    if (System.IO.Directory.Exists(dirPath))
    {
        try
        {
            // initalize temp filenam
            string filename = System.DateTime.Now.ToString("yyyymmdd_hhmmss_fff") + ".tmp";
            // try to create temp file
            System.IO.File.Create(dirPath + filename).Close();
            // check file exists and set return result
            if (System.IO.File.Exists(dirPath + filename))
            {
                result = true;
            }
            // delete temp file
            System.IO.File.Delete(dirPath + filename);                    
        }
        catch (UnauthorizedAccessException ex)
        {
            // code to handle UnauthorizedAccessException
        }
        catch (Exception ex)
        {
            // code to handle all other exceptions
        }

    }
    return result;
}
 
Share this answer
 
Many students these days are taught defensive programming: before doing something, check up if you can do it. In many cases, this should be done, and, in many other cases, this is quite wrong, obsolete and inefficient approach. Very often, programming should be offensive: just do the operation, don't ask if you can. You can always execute code under try-catch (and most usually you should), let the exception propagate and eventually handle it. If exception was thrown due to access violation and caught, you don't have the excess. Isn't that simple?

So, I'm suggesting the simple and practical approach: don't do defensive programming, do offensive. If the permission denied exception is not thrown, the user has the access, and the operation is already done. If it was thrown — inform the user of the failure and its reason.

As simple as that.

—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900