I need to get a list of all files on a handheld device whose names fit a certain pattern, such as "ABC.XML"
I adapted code from here (Hernaldo's answer), like so:
public static List<string> GetXMLFiles(string fileType, string dir)
{
string dirName = dir; // call it like so: GetXMLFiles("ABC", "\\"); <= I think the double-whack is what I need for Windows CE device...am I right?
var fileNames = new List<String>();
try
{
foreach (string f in Directory.GetFiles(dirName))
{
if ((f.Contains(fileType)) && (f.Contains(".XML")))
{
fileNames.Add(f);
}
}
foreach (string d in Directory.GetDirectories(dirName))
{
GetXMLFiles(fileType, d);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return fileNames;
}
...but each time the method recursively calls itself (in the GetDirectories() loop), I'm passing the same old first arg. Is it possible (in Compact Framework) to do something like this instead:
public static List<string> GetXMLFiles(optional string fileType, string dir)
{
. . .
foreach (string d in Directory.GetDirectories(dirName))
{
GetXMLFiles(dir = d);
}
. . .
?
UPDATE
According to Habib, this should work (new "try" section):
try
{
string filePattern = string.Format("*{0}*.XML", fileType);
foreach (string f in Directory.GetFiles(dirName, filePattern))
{
fileNames.Add(f);
}
foreach (string d in Directory.GetDirectories(dirName))
{
GetXMLFiles(fileType, d);
}
}
Ja?
UPDATE 2
This goes along with my second response to Alan's comment below:
const string EXTENSION = ".XML";
. . .
try
{
foreach (string f in Directory.GetFiles(dirName))
{
string ext = Path.GetExtension(f);
string fileNameOnly = Path.GetFileNameWithoutExtension(f);
if ((ext.Equals(EXTENSION, StringComparison.Ordinal)) && (fileNameOnly.Contains(fileType)))
{
fileNames.Add(f);
}
}
foreach (string d in Directory.GetDirectories(dirName))
{
GetXMLFiles(fileType, d);
}
}
Optional parameters are a feature of .NET 4.0, so you won't be able to use them. The typical solution to this with a recursive function is to create two overloads for your method with different parameters.
For example,
In this case, the method which kicks off the recursion has a slightly different signature. You could do the same.
Directory.GetFiles has an overload which takes search pattern you can use that:
You can also use wildcards like
"*.XML"
which would return all XML files.