azza
azza

Reputation: 77

c# check the extension of the uploaded file

I am looking for a simple way to check the extension of the uploaded file, if it was PDF file do something, else a warning message will show that its (wrong file type), but the problem with my code is if I selected any file type instead of PDF it will show the error page with this message:

   Server Error in '/' Application.
   PDF header signature not found.
   Exception Details: iTextSharp.text.exceptions.InvalidPdfException: PDF header signature not found.



        <asp:FileUpload runat="server" ID="file1" AllowMultiple="true" />


        string fileName = Path.GetFileName(file1.FileName);
        FileInfo fi = new FileInfo(fileName);
        string ext = fi.Extension;

        if (ext == ".pdf")
        {
        //do something
        }
        else
        Label1.Text = string.Format("wrong file type");

Upvotes: 2

Views: 10245

Answers (2)

Saurabh
Saurabh

Reputation: 1631

 bool isValidFile = false;

            string[] validFileTypes = { "xlsx", "xls", "pdf" };
            string ext = Path.GetExtension(File_Uploader.PostedFile.FileName);

            for (int i = 0; i < validFileTypes.Length; i++)
            {
                if (ext == "." + validFileTypes[i])
                {
                    isValidFile = true;
                    break;
                }
            }

Upvotes: 3

ammu
ammu

Reputation: 258

to get FileName of the uploaded file

string FileName = file1.PostedFile.FileName;

to get extension of the uploaded file

string FileExtension = System.IO.Path.GetExtension(file1.PostedFile.FileName);

Upvotes: 8

Related Questions