Code Help: Subdirectory Search C#

matchoo

New member
Joined
Feb 23, 2006
Messages
1
Greetings,

I know this is prob. is easy - but I am just starting out with C# and looking to do some experiments to learn faster.

I would like a listbox to show all xml files in the current directory and all subdirectories. The xml file list should be sorted. When a user clicks on one of these files, it will open it in notepad.

Im sure this is easy to do - can you share how you would accomplish it?

Thanks

-mreider
 
Well, showing all the XML files in a directory is easy to do. Directory.GetFiles() will do most of the work for you.

Finding the XML files in subdirectories is harder, because you first have to find the (sub)directories in the directory and then do the above to find all of the files in this directory. :)
 
Finding the subdirectories should actually be pretty trivial if you are familiar with recursion (in terms of programming). As far as opening them in notepad, look into the System.Diagnostics.Process class.
 
matchoo said:
Greetings,

I know this is prob. is easy - but I am just starting out with C# and looking to do some experiments to learn faster.


Just in case you need extra information, here is a sample you can tweak.

Code:
private void OnFormLoad(object sender, EventArgs e)
{
	FolderBrowserDialog fbd = new FolderBrowserDialog();

	if (fbd.ShowDialog() == DialogResult.OK)
	{
		GetAllFiles(fbd.SelectedPath);
	}

	lbFiles.Sorted = true;
}

private void GetAllFiles(string startPath)
{
	string[] files = Directory.GetFiles(startPath, "*.xml");
	foreach (string s in files)
		lbFiles.Items.Add(s);

	string[] dirs = Directory.GetDirectories(startPath);
	foreach (string dir in dirs)
		GetAllFiles(dir);
}
 
Back
Top