简体   繁体   中英

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM