1
DirectoryInfo[] directories = 
        di.GetDirectories("*.*", SearchOption.AllDirectories);

The problem is that some folders I am not able to access thus I get an exception.

Program files for example I cannot access.

Is there any workaround for that?

Edit: Here is the code. As you can see I have configure the code so it continue if happens an exception. When it occurs I only get the message Access to the path 'C:\Arquivos de Programas' is denied. and no files or folder

How can I avoid this behavior and print on screen the ones I have permission?

Thanks

 try
{
    //Resgata todos os drivers Lógicos do Sistema
    DriveInfo[] allDrives = DriveInfo.GetDrives();

    //Cria uma lista não ordenada para os DRIVERS
    Response.Write("<ul class=\"jqueryFileTree\" style=\"display: none;\">\n");

    //Itera sobre cada driver no array
    foreach (DriveInfo drive in allDrives)
    {
        if (drive.IsReady == true)
        {
            try //GetDirectories
            {
                //Para cada driver cria um LI A 
                Response.Write("\t<li class=\"drive collapsed\"><a href=\"#\" rel=\"" + drive.ToString() + "\">" + drive.ToString() + "</a>\n");

                System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(drive.ToString());
                DirectoryInfo[] directories = di.GetDirectories("*.*", SearchOption.AllDirectories);


                Response.Write("<ul>");
                //Itera sobre os subdiretórios de cada driver
                foreach (System.IO.DirectoryInfo di_child in directories)
                {

                    Response.Write("\t<li class=\"directory collapsed\"><a href=\"#\" rel=\"" + drive + di_child.Name + "/\">" + di_child.Name + "</a>\n");
                    Response.Write("<ul>");
                    //Itera sobre todos os arquivos do diretório


                    foreach (System.IO.FileInfo fi in di.GetFiles())
                    {
                        string ext = "";
                        if (fi.Extension.Length > 1)
                        {
                            ext = fi.Extension.Substring(1).ToLower();
                        }

                        Response.Write("\t<li class=\"file ext_" + ext + "\"><a href=\"#\" rel=\"" + drive + fi.Name + "\">" + fi.Name + "</a></li>\n");
                    }// Arquivos 
                    Response.Write("</ul></li>");
                }// subdiretorio 
                Response.Write("</ul></li>");
            }
            catch (UnauthorizedAccessException e)
            {
                Response.Write(e.Message);
                continue;
            }
            catch (System.IO.DirectoryNotFoundException e)
            {
                Response.Write(e.Message);
                continue;
            }
            catch (Exception e)
            {

                Response.Write(e.Message);
                continue;
            }

        }//isReady

    }///drive
    Response.Write("</ul>");

}
catch (Exception)
{

    throw;
}  
Guilherme Longo
  • 2,278
  • 7
  • 44
  • 64
  • What are you trying to do on the directories once you've found them? – Chris Nov 27 '12 at 16:08
  • Eai Xará, brasileiro também né? estava com o mesmo problema, fiz um try catch sendo q no catch eu mostrava na lista um item escrito "Acesso Negado", funcionou aqui. obrigado. – Guilherme Golfetto May 30 '16 at 13:55

2 Answers2

2

In general there is no any workarround.

You're not allowed to change (in most cases you simply can't) permission map on the host PC. So the only think that you can do, is just catch an exception and report a user about that fact, with, may be, some suggession, how can be that issue resolved.

There may be some hacks, tricks or whatever, but, in my opinion, it's not good design. Do not hack the system, unless you're not writing viruses.

EDIT

If you worry about a fact that if single file fails on load, you directory parsing fails, you can do following:

foreach (System.IO.FileInfo fi in di.GetFiles())
{
     try{
           string ext = "";
           if (fi.Extension.Length > 1)
           {
                 ext = fi.Extension.Substring(1).ToLower();
           }

            Response.Write("\t<li class=\"file ext_" + ext + "\"><a href=\"#\" rel=\"" + drive + fi.Name + "\">" + fi.Name + "</a></li>\n");
        }
        catch(..) {
          //handle here exception raised during SINGLE file parsing
        }
}// Arquiv
Tigran
  • 61,654
  • 8
  • 86
  • 123
  • I just want to skip cheking if user has no permission to access the file... if has no permission then don´t print the folder or file... – Guilherme Longo Nov 27 '12 at 16:24
  • ah, at this point, I beleive, handling appropriate exception inside loop, is a best choice. Like an ordinary IO operation management, manageit with appropriate, or *expected*, exception handling – Tigran Nov 27 '12 at 16:46
  • the problem is.. if getDirectory or getFile reachs a file without permission the whole method fails. ;O( Even handling the code, for that specific logical driver you lose everything and the code goes to the the next logical driver – Guilherme Longo Nov 27 '12 at 18:47
  • @user1827417: if the permission for read fails on one file but you would like continue iteration over other files *in the same directory*, move you exception handling deep to the point where you read single file. – Tigran Nov 27 '12 at 18:50
  • I have update the post with the code.. I don´t really get what you mean with moving exception deeper. Please, could you help me with that? – Guilherme Longo Nov 27 '12 at 19:24
0

Yes there is, unfortunately, this is a limitation of GetDirectories.

Check out: Windows service running as system cannot access C:\users\

In the example above, the execptions occur regardless of permission level, but the same principle applies. When you hit an exception, the entire function fails.

Using PInvoke as suggested in the linked article in that post, you can at least continue on, ignoring the exceptions instead of failing outright.

Community
  • 1
  • 1
Grant H.
  • 3,689
  • 2
  • 35
  • 53
  • It really works but the method still fails so for that logical driver i get nothing. The system does not crash and I am able to search in the next logical driver but not the one that has trown an exception – Guilherme Longo Nov 27 '12 at 18:48