سؤال

Say I have a string like ".vcproj;.csproj;*.sln" and I want to show all files of these types in a directory... Windows does this all the time with open-file dialogs.

I am aware of Directory.GetFiles but it only lets me run a given search pattern so I'd have to split my input and then loop over each.

Is there no built-in functionality to do this, after all the open-file dialog does it?

.NET 2 so no LINQ cleverness is usable!

هل كانت مفيدة؟

المحلول

Try this way:

string[] formats = {".jpg", ".png", ".txt"};
var files = Directory.GetFiles("C:\\");
var neededFiles = files.
    Where(file => formats.Any(file.EndsWith)).
    ToArray();

Alternatively, for .NET 2.0:

var desiredFiles = new List<string>(files.Length);
foreach (var file in files)
{
    foreach (var format in formats)
        if (file.EndsWith(format))
        {
            desiredFiles.Add(file);
            break;
        }
}

نصائح أخرى

You can use the vertical pipe '|' for RegEx Alternation. I think your final code should look something like:

string input_files = ".vcproj;.csproj;*.sln";
string search_for = input_files.Replace(".","\.").Replace(";","|")

Directory.GetFiles("/path/to/directory",search_for)

I've never done any coding in .NET so I apologize if my syntax is off. Obviously you can save some time if your initial string of search terms starts off in valid regex form.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top