Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# check the extension of the uploaded file

Tags:

c#

pdf

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");
like image 737
azza Avatar asked Nov 29 '25 14:11

azza


2 Answers

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);
like image 144
ammu Avatar answered Dec 02 '25 05:12

ammu


 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;
                }
            }
like image 44
Saurabh Avatar answered Dec 02 '25 03:12

Saurabh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!