Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OpenFileDialog C# custom filter like 'ABC*.pdf'

Is it possible to specify custom filters like 'ABC*.pdf' which means: "Show all PDF which starts with ABC"?

I can only specify *.pdf, *.doc, *.*, etc.

Thanks Florian

like image 710
user2071938 Avatar asked Nov 08 '13 11:11

user2071938


People also ask

What OpenFileDialog does in C#?

C# OpenFileDialog control allows us to browse and select files on a computer in an application. A typical Open File Dialog looks like Figure 1 where you can see Windows Explorer like features to navigate through folders and select a file.

What is initial directory?

The InitialDirectory property is typically set using one of the following sources: A path that was previously used in the program, perhaps retained from the last directory or file operation. A path read from a persistent source, such as an application setting, a Registry or a string resource in the application.


2 Answers

Updated

Changed my solution a little after realizing the following would be better:

This is not a complete "hard filter", but making use of the FileName property should still cover your needs:

using System;
using System.Windows.Forms;

namespace TestingFileOpenDialog
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.openFileDialog1.FileName = "pro*";
            this.openFileDialog1.Filter = "Pdf Files|*.pdf";
            this.openFileDialog1.ShowDialog();
        }
    }
}

I suppose this might depend on which OS you are working with, but it did work in my case any way, on Windows 8.

I also realize that this does not filter out all irrelevant files "permanently", but it does at least provide an initial filter.

Result:
(Without pro* in the FileName-field, this will show several other PDF files).

enter image description here

like image 148
Kjartan Avatar answered Sep 16 '22 15:09

Kjartan


Yes and no.

No: Look at the MSDN, page. The filter is not used that way. It's only for the extensions.

Yes: You could write your own class that extends/mimics the OpenFileDialog, have some regular expressions to do what you want, and simply run that match against all the files in the current folder (Might take some work, but if you really want it so bad, go for it :) )

like image 39
Noctis Avatar answered Sep 17 '22 15:09

Noctis