1

i want to know how i can test if i can access a string path or not. Here is the code I use:

using System;
using System.IO;

namescpace prog1
{
    class Program
    {
        static void Main(string[] args)
        {
            string path = @"C:\Users\Admin";
            DirectoryInfo dir = new DirectoryInfo(path);
            foreach (FileInfo fil in dir.GetFiles())
            {
                //At dir.GetFiles, I get an error  saying
                //access to the string path is denied.

                Console.WriteLine(fil.Name);
            }
            Console.ReadLine();
        }
    }
}

I want to test if acces is denied (to string path) Then do the GetFiles and all that.

I've already found this: how can you easily check if access is denied for a file in .NET?

Any help?

Community
  • 1
  • 1
Máté Homolya
  • 548
  • 6
  • 10

2 Answers2

5

The simplest (and usually safest) option is to just do what you're doing now, but wrap the code in proper exception handling.

You can then catch the UnauthorizedAccessException from GetFiles (and potentially a SecurityException from the DirectoryInfo constructor, depending on the path) explicitly, and put your handling logic there.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
2

Can do something like this:

static void Main(string[] args)
{
     string path = @"C:\Users\Admin";
     DirectoryInfo dir = new DirectoryInfo(path); 
     FileInfo[] files = null;
     try {
            files = dir.GetFiles();
     }
     catch (UnauthorizedAccessException ex) {
         // do something and return
         return;
     }

     //else continue
     foreach (FileInfo fil in files )
     {
        //At dir.GetFiles, I get an error  saying
        //access to the string path is denied.

         Console.WriteLine(fil.Name);
      }
      Console.ReadLine();
}
Tigran
  • 61,654
  • 8
  • 86
  • 123