Click here to Skip to main content
15,918,049 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
My goal in this part of my application is to warn the user if they select a directory/folder for use as a report depot that is read only, not accessible to them.
Based on several solutions from this web site and others, I have tried the following

DirectoryInfo di = new DirectoryInfo(sConnectionFolder);
if ((di.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
// WARN THE USER

My problem is, when testing with a read-only folder, the di.Attributes property's value is merely 'Directory', and does not contain the flag/component for read-only.
from the debugger:
di.Attributes = Directory
So my warning code is never executed.

What I have tried:

Other attempts:

if (di.Attributes.HasFlag(FileAttributes.ReadOnly))

// and steering clear of DirectoryInfo, just using FileInfo:
FileAttributes file_attr = (new FileInfo(sConnectionFolder)).Attributes;

// and lastly, using File class to get the attributes:
FileAttributes fa = File.GetAttributes(sConnectionFolder);

// all with the same result: Directory for the attribute value

// Why is the read-only flag not present?
Posted
Updated 11-Apr-20 12:16pm

Attributes is never going to tell you.

The really quick'n'easy way to figure it out is to attempt to create a file in that folder and see what happens. If it succeeds, the user running your code has the permissions to do save there. If not, well, you tell the user to pick another folder.
 
Share this answer
 
Comments
uniqman 11-Apr-20 19:53pm    
Thanks, that is what I will do. But I am surprised there isn't a .NET method that would provide the answer.
Try the DirectoryInfo.GetAccessControl Method (System.IO) | Microsoft Docs[^] - it should tell you what you want (possibly by throwing an access violation exception, I can't tell ATM, i'm on a tablet).
 
Share this answer
 
Comments
uniqman 11-Apr-20 19:48pm    
Thanks for replying. I tried this just now and it does not throw an exception, and the folder is such that I cannot create a text file in it (via File Explorer). I was thinking I will just have to do a trial file create (like the solution below), but I was hoping there was a more sophisticated method.
Dave Kreskowiak 11-Apr-20 22:13pm    
There isn't a direct method because the Security system is pretty complex, having to deal with impersonation. The "current user" may be obvious to you sitting at the keyboard, but in the real world, that's not a simple concept. Throw various levels of impersonation into the mix and things get complex real quick.

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