65.9K
CodeProject is changing. Read more.
Home

Scanning Folders On A Network Share

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.77/5 (6 votes)

Jun 6, 2010

CPOL
viewsIcon

18315

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:
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.