質問

I want to apply a filter on string [] of FileNames that i get from Directory.GetFiles() without opening it in OpenFileDialog.

Is there any way I can apply all these filters (that i usually would apply to OpenFileDialog) e.g:

openFileDialog.Filter = "Bitmap Images (*.bmp)|*.bmp|" +
                          "JPEG Images (*.jpeg, *.jpg)|*.jpeg;*.jpg|" +
                          "PNG Images (*.png)|*.png|" + ...;

to the string [].

I basically want to select Folder from FolderBrowserDialog and select only selected files from the Folder - was trying find some way to do this silently(setting parameters to OpenFileDialog but not opening it ).

I just tried the following .:

OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.InitialDirectory = folderdialog.SelectedPath; // here I get my folder path 
            openFileDialog.Filter = "Bitmap Images (*.bmp)|*.bmp|" +
                          "JPEG Images (*.jpeg, *.jpg)|*.jpeg;*.jpg|" +
                          "PNG Images (*.png)|*.png";                
            string [] fnms = openFileDialog.FileNames; // I wished this string arry to get poplulated with filtered file list - but doh! Obviously it didn't.

Can anyone help me with find a solution to this. Is there any way to invoke OpenFiledDialog silently ? Or will there be any LINQ query for this problem or anything as such .? [I'm a novice - yet learner]

Any help will be much appreciated. Thanks in advance

役に立ちましたか?

解決

I don't think calling Directory.GetFiles more than once will be a good idea because it is an IO operation. I recommend that you do something like:

static string[] GetFiles(string directory, params string[] extensions)
{
    var allowed = new HashSet<string>(extensions, StringComparer.CurrentCultureIgnoreCase);

    return Directory.GetFiles(directory)
                    .Where(f => allowed.Contains(Path.GetExtension(f)))
                    .ToArray();
}

static void Main(string[] args)
{
    string[] files = GetFiles(@"D:\My Documents", ".TXT", ".docx");
    foreach(var file in files)
    {
        Console.WriteLine(file);
    }
}

他のヒント

Untested but should work

var formats = new string[]{"*.jpg","*.mp3"}
formats.SelectMany(format => Directory.EnumerateFiles(dirpath, 
                        format, SearchOption.AllDirectories)
       .ToArray();

I would take a look at the following article: http://www.beansoftware.com/ASP.NET-FAQ/Multiple-Filters-Directory.GetFiles-Method.aspx

It is basically a wrapper for the GetFiles function that will take a string very similar to the one you give to the OpenFolderDialog and will return a string array (string[]) of files that match the patterns. (It's just a recursive Direectory.GetFiles)

E.g.:

getFiles(path, ".bmp|.jpg") etc.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top