HOW TO CHECK FILE FORMAT

Anurag Sharma

Total Post:40

Points:280
Posted by  Anurag Sharma
.NET 
 1455  View(s)
Ratings:
Rate this:

Hi Guys

 

the allowed file format is only PDF file, how to check the file format and display error message if the uploaded file is not PDF before proceeding to update database. The following code always displays the file is not recognized even the file is PDF and also the database not updated.

 

 string filePath = FileUpload1.PostedFile.FileName;

    string filename = Path.GetFileName(filePath);

    string ext = Path.GetExtension(filename);

    string contenttype = String.Empty;

 

    switch (ext)

    {

        case ".pdf":

 

            contenttype = "application/pdf";

 

            break;

        default:

            System.Console.WriteLine("File format not recognised. Only PDF format allowed");

            break;

    }

    if (contenttype != String.Empty)

    {

        Stream fs = FileUpload1.PostedFile.InputStream;

        BinaryReader br = new BinaryReader(fs);

        Byte[] bytes = br.ReadBytes((Int32)fs.Length);

 

        string classNmae = ddClass.Text.Split('~')[0] + ddClass.Text.Split('1');

        com.Parameters.Clear();

        com.CommandText = "UPDATE [Marking] SET [fileName]=@fileName, [fileType]=@fileType, [type]=@typ,[submissionDate]=@sd, [filePath]=@fp where [class_id]=@cid AND [module_id]=@mid  AND [student_id]= '" +Session["id"].ToString() + "'";

        com.Parameters.Add("@cid", SqlDbType.VarChar).Value = ddClass.Text.Split('~')[0];

        com.Parameters.Add("@mid", SqlDbType.VarChar).Value = ddClass.Text.Split('~')[1];

        com.Parameters.Add("@fileName", SqlDbType.VarChar).Value = filename;

        com.Parameters.Add("@fileType", SqlDbType.VarChar).Value = "application/pdf";

        com.Parameters.Add("@typ", SqlDbType.VarChar).Value = txtType.Text;

        com.Parameters.Add("@sd", SqlDbType.VarChar).Value = DateTime.Now;

        com.Parameters.Add("@fp", SqlDbType.Binary).Value = bytes;

 

        com.ExecuteNonQuery();

 

    }

    else

    {

 

        lb.Text = "File format not recognised." +

 

          " Upload Word formats";

 

    }

 

Thanks

  1. Allen Scott

    Post:46

    Points:324
    Re: how to check file format

    Try this:

    if (FileUpload1.HasFile)
    {
        HttpPostedFile myPostedFile = FileUpload1.PostedFile;
        FileInfo finfo = new FileInfo(myPostedFile.FileName);
        if (finfo.Extension.Equals(".pdf", StringComparison.InvariantCultureIgnoreCase))
        {
            //do the operation
        }
    }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!