You should define the return type of the
SearchFilesRecursive
method as
IEnumerable<string>
.
And use the
yield[
^] statement for returns (that will need some refactoring from you).
Then you would have to modify your search-code:
foreach (string s in htmlobj) {
listBox1.Items.Add(s);
}
But then, if your search-method runs on the main thread, there are little chances that you will see any update of the listbox. You have to execute the search on another thread.
BackgroundWorker Class[
^] is a good and rather easy way to achieve that.
But, most important, I find your search algorithm too much complex with your list and stack; technically the only thing you need is a list. You should reconsider its design.
Moreover, your algorithm is not strictly recursive, as it never actually calls itself.
Left to quit the recursive way, your requirement could be simplified to:
public IEnumerable<string> SearchFiles(string directory, string pattern) {
foreach (string s in Directory.GetFiles(dir, pattern, SearchOption.AllDirectories)) {
yield return s;
}
}