what is the best way to check in C# .NET if a directory has access to list files or a unauthorized access exception would rise -


how check in best way in .net 2.0 c# if have access specified directory listing top directory files e.g. system directory or system volume information folder etc. code looks this, think not best way check since produces exception each time handled check function , returning based on result.

i use function doesn't throw error check if in specified directory access list files or maybe code can improved or optimized. might have check through thousand directories if exists access or not. raising thousand exceptions might cause problem, don't know.

//here code using system.io;  private void button1_click(object sender, eventargs e) {     messagebox.show(directorycanlistfiles("c:\\windows\\prefetch").tostring()); }  public static bool directorycanlistfiles(string directorypath) {     try     {         directory.getfiles(directorypath, "*", searchoption.topdirectoryonly);     }     catch { return false; }     return true; } 

the best way check permission, try access direcoty (read/write/list) & catch unauthorizedaccessexception.

however reason out there, if want check permissions, following code should satisfy need. need read access rules directory.

private bool directorycanlistfiles(string folder) {     bool hasaccess = false;     //step 1. username which, app domain code has been executing     string executinguser = system.security.principal.windowsidentity.getcurrent().name;     ntaccount acc = new ntaccount(executinguser);     securityidentifier secid = acc.translate(typeof(securityidentifier)) securityidentifier;      directorysecurity dirsec = directory.getaccesscontrol(folder);      //step 2. directory permission details each user/group     authorizationrulecollection authrules = dirsec.getaccessrules(true, true, typeof(securityidentifier));                              foreach (filesystemaccessrule ar in authrules)     {         if (secid.compareto(ar.identityreference securityidentifier) == 0)         {             var filesystemrights = ar.filesystemrights;             console.writeline(filesystemrights);              //step 3. check file system rights here, read / write required             if (filesystemrights == filesystemrights.read ||                 filesystemrights == filesystemrights.readandexecute ||                 filesystemrights == filesystemrights.readdata ||                 filesystemrights == filesystemrights.listdirectory)             {                 hasaccess = true;             }         }     }     return hasaccess; } 

Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

.htaccess - Matching full URL in RewriteCond -