IMHO, the linked question I propose as a duplicate should suffice. But in the interest of completeness and clarity, here is what I mean you to do:
IEnumerable<string> EnumerateSpecificFiles(
string directory, string initialTextForFileName)
{
foreach (string file in Directory.EnumerateFiles(directory))
{
if (file.StartsWith(initialTextForFileName, StringComparison.OrdinalIgnoreCase))
{
yield return file;
}
}
}
This avoids having the entire list of file names in memory, while still allowing you to perform your case-insensitive search.
EDIT:
Given that it turns out you are using an earlier version of Mono, which does not include the Directory.EnumerateFiles()
method, your next best option is to go ahead and implement that method yourself using p/invoke (perhaps even just copy the implementation from the current Mono sources).
As a hack, you could at least restrict the number of files returned by Directory.GetFiles()
by applying a partial filter. E.g.:
IEnumerable<string> EnumerateSpecificFiles(
string directory, string initialTextForFileName)
{
char[] initialCharacters =
{
char.ToLowerInvariant(initialTextForFileName[0]),
char.ToUpperInvariant(initialTextForFileName[0])
};
foreach (char ch in initialCharacters)
{
foreach (string file in Directory.GetFiles(directory, ch + "*"))
{
if (file.StartsWith(initialTextForFileName, StringComparison.OrdinalIgnoreCase))
{
yield return file;
}
}
}
}
Finally, you may consider just getting all the files in the directory all at once using the Directory.GetFiles()
method and filtering that result as above. You may find it works well enough.