954,515 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

searching for files

Hi,

At the moment i'm trying to locate xml files to use their content. I would like to be able find all files that have a particular pattern in their name (for example student_James.xml; student_Chris.xml so "student" would be the pattern). I want to be able to do this using a drive that is selected from a comboBox (i've figured out how to get a list of all possivle drives).

As only the drive and name pattern is known (not the full directort), i want to be able to locate the files using only the drive and the name pattern.

Any help would be greatly appreciated

Thanks

Chris

ChrisHunter
Posting Whiz in Training
276 posts since Feb 2011
Reputation Points: 36
Solved Threads: 28
 

Every drive has a root folder know as "\".
So starting at drive letter to search and root dir (IE: "F:\") you can use this to obtain a System.IO.DirectoryInfo

var RootDir = new System.IO.DirectoryInfo("F:\\")

Just be aware that you need to specify a doube backslash in order to be interpreted a s a single one.

At this point the root dir directoy info has a very useful function EnumerateFiles that, with the second parameter SearchOption.AllDirectories will do the trick.

Hope this helps.

lolafuertes
Master Poster
793 posts since Oct 2008
Reputation Points: 120
Solved Threads: 166
 

Another useful method that only requires one line is Directory.GetFiles :

string[] matchingFiles = Directory.GetFiles("F:\\", "student_*.xml", SearchOption.AllDirectories);
var RootDir = new System.IO.DirectoryInfo("F:\\")

Just be aware that you need to specify a doube backslash in order to be interpreted a s a single one.

I recommend using @-style string literal for the search path in this case, as it results in code that in my opinion is a little clearer and easier to read:

string[] matchingFiles = Directory.GetFiles(@"F:\", "student_*.xml", SearchOption.AllDirectories);
gusano79
Posting Pro
521 posts since May 2004
Reputation Points: 182
Solved Threads: 77
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: