• 0

C# Recursive Directory traverse


Question

I have used the code below from Microsoft however, it does not seem to search the root path (sDir when method is first called)

e.g

/* it does not return results in root path

* when search C:\Text test\ as the path sDir = @"C:\Text test\";

* C:\Text test\txtFile.Textt will not be found. when it meets the filter so should be found

*/

Does anyone know what is wrong or what I should add to make it search the "root" directory?

Thanks

http://support.microsoft.com/kb/303974

void DirSearch(string sDir) 
{
	try	
	{
	   foreach (string d in Directory.GetDirectories(sDir)) 
	   {
		foreach (string f in Directory.GetFiles(d, txtFile.Text)) 
		{
		   lstFilesFound.Items.Add(f);
		}
		DirSearch(d);
	   }
	}
	catch (System.Exception excpt) 
	{
		Console.WriteLine(excpt.Message);
	}
}

Link to comment
Share on other sites

5 answers to this question

Recommended Posts

  • 0

void DirSearch(string sDir)
{
	try	
	{
		foreach (string f in Directory.GetFiles(sDir, txtFile.Text))
		{
		   lstFilesFound.Items.Add(f);
		}

	   foreach (string d in Directory.GetDirectories(sDir))
	   {

		DirSearch(d);
	   }
	}
	catch (System.Exception excpt)
	{
		Console.WriteLine(excpt.Message);
	}

This ought to fix it, I guess. Havn't put too much thought in to it, check yourself. PM me if it doesn't work or if you ask me something.

Link to comment
Share on other sites

  • 0

With .Net 2.0 you can use the following:

void DirSearch(string sDir)
{
	try	
	{
		foreach (string f in Directory.GetFiles(sDir, txtFile.Text, SearchOption.AllDirectories))
		{
		   lstFilesFound.Items.Add(f);
		}
	}
	catch (System.Exception excpt)
	{
		Console.WriteLine(excpt.Message);
	}
}

Link to comment
Share on other sites

  • 0

Cool thanks for that amrinders87. looks a lot nicer on paper as well and from the April 07 MSDN docs

"If you choose AllDirectories in your search and the directory structure contains a link that creates a loop, the search operation enters an infinite loop."

Seems like it iterates its way through the directory tree which should use less resources.

UPDATE: WOW this is sooo much faster than recursive method

Link to comment
Share on other sites

  • 0

Sorry for double post but they a week or so apart.

 foreach (string f in Directory.GetFiles(sDir, txtFile.Text, SearchOption.AllDirectories))

It seems that this does not always work when searching the root drive

for example if you get it to search c:\

it will complete almost instantly saying it is complete when it hasn't performed the search at all.

anyone have any ideas?

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.