Máté Homolya
Máté Homolya

Reputation: 708

How do I check if an access to a string path is denied?

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?

Upvotes: 1

Views: 4066

Answers (2)

Tigran
Tigran

Reputation: 62248

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();
}

Upvotes: 2

Reed Copsey
Reed Copsey

Reputation: 564333

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.

Upvotes: 5

Related Questions