c# Search for all emtpy folders

Get help on programming - C++, Java, Delphi, etc.
Post Reply
geraldhum
Registered User
Posts: 199
Joined: 13 Feb 2009, 12:59

c# Search for all emtpy folders

Post by geraldhum »

H Guys

I am trying to search for all empty folders on my pc.

I am getting this error: "Access to the path 'd:\System Volume Information' is denied."

here is the code

Code: Select all


  DirectoryInfo di = new DirectoryInfo(@"d:\")
           
  DirectoryInfo[] dir = di.GetDirectories("*.*", SearchOption.AllDirectories );
 
  foreach (DirectoryInfo d in dir)
                {
                    FileInfo[] f = d.GetFiles();
                    if (f.Length == 0)
                    {
                      listBox1.Items.Add(f.ToString());
                    }
                }

Can anyone please help me with this.







User avatar
Ron2K
Forum Technical Administrator
Posts: 9050
Joined: 04 Jul 2006, 16:45
Location: Upper Hutt, New Zealand
Contact:

Re: c# Search for all emtpy folders

Post by Ron2K »

"System Volume Information" is a protected operating system folder, that's why you can't access it.

Having a look at your code, I spotted two things:
  1. You need to be able to handle the cases where the operating system denies you access to the folder that you're trying to view.
  2. You're also not moving down the entire subfolder tree; instead, you're only going one level down. This is a situation where use of recursion would be perfect.
My approach to your problem would look like this:

Code: Select all

        public static void SearchEmptyFolders(DirectoryInfo baseFolder)
        {
            try
            {
                FileInfo[] fileList = baseFolder.GetFiles();
                if (fileList.Length == 0)
                {
                    Console.WriteLine("Folder {0} is empty.", baseFolder.FullName);
                }

                DirectoryInfo[] subFolders = baseFolder.GetDirectories();
                foreach (DirectoryInfo subfolder in subFolders)
                {
                    SearchEmptyFolders(subfolder);
                }
            }
            catch (UnauthorizedAccessException)
            {
                Console.WriteLine("Folder {0} could not be accessed.", baseFolder.FullName);
            }
        }
Kia kaha, Kia māia, Kia manawanui.
geraldhum
Registered User
Posts: 199
Joined: 13 Feb 2009, 12:59

Re: c# Search for all emtpy folders

Post by geraldhum »

thanks alot:), going to read up on recursion now.
hobojvr
Registered User
Posts: 47
Joined: 09 May 2006, 02:00
Location: BFN
Contact:

Re: c# Search for all emtpy folders

Post by hobojvr »

Go and google "recursion". Without reading a single hit you'll know how it works. One of those special google search words :P
RuadRauFlessa
Registered User
Posts: 20576
Joined: 19 Sep 2003, 02:00
Location: Bloodbank

Re: c# Search for all emtpy folders

Post by RuadRauFlessa »

Yeah you might even find a recursive link somewhere in there :twisted:

Also if you want to make the code a tad more robust rather than just breaking out of the loot and causing other problems you might want to try using the System.Security.AccessControl.DirectorySecurity Class... You can check the security on the folder and see if you have rights. If you don't simply don't add it to the list or output. I assume you would actually like to do something with the list of empty folders once the recursive function if finished returning them all other than just writing them to the console. If so just slapping a try catch of the whole thing will result in you not getting back a result from the recursive function which in my opinion is lame.
:rock: :rock: :rock: :rock: :rock: :rock: :rock: :rock: :rock: :rock:
Spoiler (show)
Intel Core i7-2600k @ 3.4GHz
Corsair Vengence 2x4GB DDR3 2000MHz
Thermaltake Toughpower 850W
ASUS nVidia GTX560 1GB
CoolerMaster HAF 932
geraldhum
Registered User
Posts: 199
Joined: 13 Feb 2009, 12:59

Re: c# Search for all emtpy folders

Post by geraldhum »

busy studding for 70-536 and haven't got to the security yet, but will check it out.

checked google and the first link is http://en.wikipedia.org/wiki/Recursion

Thanks
Bladerunner
Registered User
Posts: 14338
Joined: 04 Sep 2004, 02:00
Processor: i386DX Sooper
Motherboard: A blue one
Graphics card: A red one
Memory: Hard drive
Location: On a Möbius strip
Contact:

Re: c# Search for all emtpy folders

Post by Bladerunner »

But slapping a try catch within the foreach will work very well.
RuadRauFlessa
Registered User
Posts: 20576
Joined: 19 Sep 2003, 02:00
Location: Bloodbank

Re: c# Search for all emtpy folders

Post by RuadRauFlessa »

Recursion is cool.. but you have to look out for your stack... You can easily cause a stack overflow. Now on 32 and 64bit OS's the chance of it happening is remote but it can still happen.

just a simple template for recursive functions in C#

Code: Select all

public object Recursive(object value)
{
    object result;
    result = (new Random()).Next(1, 100);
    foreach(object o in objects)
    {
        result += Recursive(o);
    }
    return result;
}
Quick and dirty way of getting past the obstacle. Then you can actually use the result rather than just have it printed to the console.

Code: Select all

    public static System.Collections.ArrayList SearchEmptyFolders(System.IO.DirectoryInfo baseFolder)
    {
        System.Collections.ArrayList result = new ArrayList();
        try
        {
            System.IO.FileInfo[] fileList = baseFolder.GetFiles();
            if (fileList.Length == 0)
            {
                result.Add(baseFolder.FullName);
            }

            System.IO.DirectoryInfo[] subFolders = baseFolder.GetDirectories();
            foreach (System.IO.DirectoryInfo subfolder in subFolders)
            {
                result.AddRange(SearchEmptyFolders(subfolder));
            }
        }
        catch (UnauthorizedAccessException) {}
        return result;
    }
Bladerunner wrote:But slapping a try catch within the foreach will work very well.
No it won't as the exception is on the current folder not on the children. You get it from

Code: Select all

System.IO.FileInfo[] fileList = baseFolder.GetFiles();
or

Code: Select all

System.IO.DirectoryInfo[] subFolders = baseFolder.GetDirectories();
but the exception is still for the current folder. As such it won't even get to the loop.
:rock: :rock: :rock: :rock: :rock: :rock: :rock: :rock: :rock: :rock:
Spoiler (show)
Intel Core i7-2600k @ 3.4GHz
Corsair Vengence 2x4GB DDR3 2000MHz
Thermaltake Toughpower 850W
ASUS nVidia GTX560 1GB
CoolerMaster HAF 932
User avatar
Ron2K
Forum Technical Administrator
Posts: 9050
Joined: 04 Jul 2006, 16:45
Location: Upper Hutt, New Zealand
Contact:

Re: c# Search for all emtpy folders

Post by Ron2K »

Having said all that - when I tested the code snippet I posted earlier, I found that if you're getting access denied to a particular folder, you're extremely likely to get access denied for all its subfolders as well; hence I considered not running the loop in this scenario acceptable. Obviously, in a totally different scenario, you may want/need to still run the loop.
geraldhum wrote:thanks alot:), going to read up on recursion now.
The key to understanding recursion is to begin by understanding recursion. The rest is easy. :wink:
Kia kaha, Kia māia, Kia manawanui.
RuadRauFlessa
Registered User
Posts: 20576
Joined: 19 Sep 2003, 02:00
Location: Bloodbank

Re: c# Search for all emtpy folders

Post by RuadRauFlessa »

Ron2K wrote:Having said all that - when I tested the code snippet I posted earlier, I found that if you're getting access denied to a particular folder, you're extremely likely to get access denied for all its subfolders as well; hence I considered not running the loop in this scenario acceptable. Obviously, in a totally different scenario, you may want/need to still run the loop.
In that totally different scenario you still won't be able to as access rights filter down. If you don't have the read access to check for files in the folder you won't be able to check for folders either. So that if you have one of those scenarios where you have to look for a folder you have no rights to enumerate but have rights in the "invisible" folder, you would need to have the exact path of the "invisible" folder first.

Code: Select all

Folder1 [RW]
   Folder1.1 [RW]
   Folder1.2 [RW]
Folder2 [--]
   Folder2.1 [--]
   Folder2.2 [--]
   Folder2.3 [RW]
      Folder2.3.1 [RW]
      Folder2.3.2 [RW]
Folder3 [RW]
   Folder3.1 [RW]
Say that if you have no access to Folder2 but you have access to Folder2.3 then you won't be able to use Folder2 in order to enumerate Folder2.1, Folder2.1 and Folder2.3. You can however specify the full path to Folder2.3 and enumerate Folder2.3.1 and Folder2.3.2
:rock: :rock: :rock: :rock: :rock: :rock: :rock: :rock: :rock: :rock:
Spoiler (show)
Intel Core i7-2600k @ 3.4GHz
Corsair Vengence 2x4GB DDR3 2000MHz
Thermaltake Toughpower 850W
ASUS nVidia GTX560 1GB
CoolerMaster HAF 932
Post Reply