tag:blogger.com,1999:blog-6698224.post-1080670133558609242004-03-30T11:48:00.005-06:002004-08-11T10:38:40.720-05:00How to recursively search a subdirectory or a file in a given directory<span style="font-family:trebuchet ms;"><span style="font-size:85%;">The question is a little tricky, because we immediately think about write a recursive method, but there are some issues that you might want to considerate; Think about the <strong>Call Stack</strong>, what if the directory is too deep, enough to run into a <strong>StackOverflowException</strong> exception, or simple as you are paying a performance penalty.
<br />
<br />Instead, try to use a Stack to remember the directories to look up:</spam>
<br /></span></span><span style="font-family:arial;"><span style="font-size:78%;"></span></span>
<br /><span style="font-family:arial;"><span style="font-size:78%;">sealed class App {
<br /> static void Main() {
<br /> StringCollection results = FindDirectory("c:\\Development", "compressionsink.dll", "*");
<br /> foreach(string value in results)
<br /> Console.WriteLine(value);
<br /> }
<br /> public StringCollection FindDirectory(string root, string value, string searchPattern)
<br /> {
<br /> StringCollection results = new StringCollection();
<br /> Stack stack = new Stack();
<br /> stack.Push(root);
<br /> while(stack.Count > 0) {
<br /> string currentDir = stack.Pop().ToString();
<br /> if(0 == string.Compare(Path.GetFileName(currentDir), value, true, CultureInfo.InvariantCulture)) {
<br /> results.Add(currentDir);
<br /> }
<br /> foreach(string path in Directory.GetFiles(currentDir, searchPattern)) {
<br /> string ok = Path.GetFileName(path);
<br /> if(0 == string.Compare(ok, value, true, CultureInfo.InvariantCulture)) {
<br /> results.Add(path);
<br /> }
<br /> }
<br /> foreach(string dir in Directory.GetDirectories(currentDir)) {
<br /> stack.Push(dir);
<br /> }
<br /> }
<br /> return results;
<br /> }
<br />}</spam></span></span>
<br />Danielhttp://www.blogger.com/profile/17636031092965440114noreply@blogger.com