How can I search for a file?
hello!
I have 4 strings which represent 4 file names...
I want to search my computer for these strings, so if one of them is
found, the search function will break and the full path of the file will be
returned...
how can I do that in C#?
thanks!!
:wave:
Re: How can I search for a file?
Code:
public string FindFile(string rootFolder, string fileName)
{
string filePath = System.IO.Path.Combine(rootFolder, fileName);
// Check for the file in the current folder.
if (System.IO.File.Exists(filePath))
return filePath;
// Check for the file in subfolders.
foreach (string subfolder in System.IO.Directory.GetDirectories(rootFolder))
{
filePath = this.FindFile(subfolder, fileName);
if (filePath != null)
return filePath;
}
// The file was not found.
return null;
}
Re: How can I search for a file?
thanks jmcilhinney!!
now, if I want to scan the entire computer (starting with drive c, the d and
so on...) what string should I put in the 'rootFolder' paramater?
:wave:
Re: How can I search for a file?
Put code somewhere to keep passing the drives (their paths) into the function.
and to get all drives:
System.IO.DriveInfo.GetDrives()
Look it up in the object browser to see the return type, and you can even make it search 'just harddisks' (by DriveType)
Re: How can I search for a file?
Just be aware that DriveInfo is new for .NET 2.0. If you're using 1.x this option is not available to you. If that's the case then post back and we can supply an alternative.
Re: How can I search for a file?
Oh, ya.
System.IO.Directory.GetLogicalDrives()
would probably do the trick.
Re: How can I search for a file?
i posted something in the code bank a while back too...search for it there, might be useful, or not :)