Click here to Skip to main content
15,884,298 members
Articles / Programming Languages / C#
Tip/Trick

Scanning Folders On A Network Share

Rate me:
Please Sign up or sign in to vote.
4.77/5 (6 votes)
6 Jun 2010CPOL 17.9K   8   1
It's not as simple as just calling DirectoryInfo.GetFiles()
Today, I was writing a quick-n-dirty application to scan my HTPC for .ISO files (all Windows boxes on my LAN are Windows 7 machines), and encountered a minor issue. If I executed a call to DirectoryInfo.GetFiles(pathname, SearchOptions.AllDirectories), the app would throw an exception saying access to the path was denied. I was kind of surprised at that because I have an (admin) account on every box, and honestly didn't anticipate this exception.

I ended up have to write a recursive method to accomplish my goal:

C#
private void RecursiveScan(string folder)
{
    DirectoryInfo dirinfo = new DirectoryInfo(folder);
    FileSystemInfo[] fsInfo = dirinfo.GetFileSystemInfos("*.");
    if (fsInfo.Length > 0)
    {
        foreach(FileSystemInfo info in fsInfo)
        {
            RecursiveScan(System.IO.Path.Combine(folder, info.Name));
        }
    }
    m_filesList.AddRange(dirinfo.GetFiles("*.iso", SearchOption.AllDirectories));
    m_filesList.AddRange(dirinfo.GetFiles("*.mkv", SearchOption.AllDirectories));
}


It was a bit annoying to have to do, but hey, that's what programming is all about, right?

One thing to be aware of - when using recursive methods, you can quickly overwhelm the stack and run out of memory (and unwinding a recursive method can introduce a moderate performance hit, so be mindful of how recursive your method is, and use the technique sparingly.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Paddedwall Software
United States United States
I've been paid as a programmer since 1982 with experience in Pascal, and C++ (both self-taught), and began writing Windows programs in 1991 using Visual C++ and MFC. In the 2nd half of 2007, I started writing C# Windows Forms and ASP.Net applications, and have since done WPF, Silverlight, WCF, web services, and Windows services.

My weakest point is that my moments of clarity are too brief to hold a meaningful conversation that requires more than 30 seconds to complete. Thankfully, grunts of agreement are all that is required to conduct most discussions without committing to any particular belief system.

Comments and Discussions

 
GeneralThe MSDN docs make clear that using SearchOption.AllDirector... Pin
tonyt6-Jun-10 18:38
tonyt6-Jun-10 18:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.