0

I want to list all files in drive and i m also trying this code in c#. but i get unaurthorizedfileaccess exception. plzz give me right solution so i can go ahead in my work....

try
{
    var files = new List<string>(Directory.GetFiles("E:\", "*.*", SearchOption.AllDirectories));
    Method(files);           
}
catch(Exception e)
{
    Console.WriteLine(e);
}
static void Method(List<string> files)
{
    foreach (string file in files)
    {
        Console.WriteLine(file);
    }
    Console.WriteLine(files.Count);
}
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263

2 Answers2

2

You can have method to get files in directory and recursively call that one as below

static void GetAllFiles(string path, IList<string> files)
{
    try
    {
        Directory.GetFiles(path).ToList()
            .ForEach(f => files.Add(f));

        Directory.GetDirectories(path).ToList()
            .ForEach(f => GetAllFiles(f, files));
    }
    catch (UnauthorizedAccessException ex)
    {
       //Console.WriteLine(ex);
    }
}

then you can print the results as below

 var files = new List<string>();
 GetAllFiles(path ,files); 
 Method(files);   
Damith
  • 62,401
  • 13
  • 102
  • 153
1

That's right your app could not have access rights to some folders (for ex: system folders), so you need to handle this case. It's seems it's imposible to do this in one line. You need something like this:

    void DiscoverDirs(string where, List<string> files)
    {
        try
        {
            files.AddRange(Directory.GetFiles(where));
            foreach (var dir in Directory.GetDirectories(where))
            {
                DiscoverDirs(dir, files);
            }
        }
        catch
        {
            // no access fo this dir
        }
    }

And calling syntax:

   var list = new List<string>();
   DiscoverDirs("E:\\", list);

Notice that it could take a looooonnnng time.

Tony
  • 7,345
  • 3
  • 26
  • 34