BB987
BB987

Reputation: 181

allowing only pdf files to be uploaded

I have a browse button in my windows form application and i wanted to only filter down to the option of choosing pdf files. So in the browse file window only pdf files will be visible and not showing .doc or any kind of document format.

private void btnSelectFile_Click(object sender, EventArgs e)
    {
        var dlg = new OpenFileDialog();
        var res = dlg.ShowDialog();
        if (res == DialogResult.OK)
        {
            DocumentUNCPath.Text = dlg.FileName;
        }
    }

Upvotes: 0

Views: 4159

Answers (4)

Chris
Chris

Reputation: 2895

You'll want to set the filter property on your dlg object like this:

var dlg = new OpenFileDialog();
dlg.Filter = "*.pdf";
var res = dlg.ShowDialog();
if (res == DialogResult.OK)
{
    DocumentUNCPath.Text = dlg.FileName;
}

Upvotes: 2

gzaxx
gzaxx

Reputation: 17590

Add this:

dlg.Filter = "PDF files|*.pdf";

Upvotes: 2

Mike Perrenoud
Mike Perrenoud

Reputation: 67898

You want to use the Filter property of the OpenFileDialog.

dlg.Filter = "PDF Files|*.pdf"

The portion to the left of the | can be anything, I just gave you an example, but it's what's shown to the user. The portion to the right of the | is the actual Windows filter.

Upvotes: 1

Lloyd
Lloyd

Reputation: 29668

Firstly you need to apply a filter first to the OpenFileDialog such as:

dlg.Filter = "PDF Files|*.pdf";

However, that doesn't stop them from forcing through a file (which they can do). You can again check the filename again after they click on OK but this is no guarantee that the file you get will be a PDF.

To be safe you could use a PDF library either locally or server side to try and open the PDF file and see if it really is such.

Upvotes: 9

Related Questions