I need to test if a user can write to a folder before actually attempting to do so.
I've implemented the following method (in C# 2.0) that attempts to retrieve the security permissions for the folder using Directory.GetAccessControl() method.
private bool hasWriteAccessToFolder(string folderPath)
{
try
{
// Attempt to get a list of security permissions from the folder.
// This will raise an exception if the path is read only or do not have access to view the permissions.
System.Security.AccessControl.DirectorySecurity ds = Directory.GetAccessControl(folderPath);
return true;
}
catch (UnauthorizedAccessException)
{
return false;
}
}
When I was googling how to test for write access nothing like this came up and it appeared very complicated to actually test permissions in Windows. I am concerned that I am over-simplifying things and that this method is not robust, although it does seem to work.
Will my method to test if the current user has write access work correctly?
I used the same function for check if file hasWriteAccess:
You have a potential race condition in your code--what happens if the user has permissions to write to the folder when you check, but before the user actually writes to the folder this permission is withdrawn? The write will throw an exception which you will need to catch and handle. So the initial check is pointless. You might as well just do the write and handle any exceptions. This is the standard pattern for your situation.
I appreciate that this is a little late in the day for this post, but you might find this bit of code useful.
Drop that into a Console app and see if it does what you need.
Try this:
I faced the same problem: how to verify if I can read/write in a particular directory. I ended up with the easy solution to...actually test it. Here is my simple though effective solution.
Hope it helps !
You can try following code block to check if the directory is having Write Access. It checks the FileSystemAccessRule.