Home > DeveloperSection > Forums > how to check file format
Anurag Sharma
Anurag Sharma

Total Post:40

Points:280
Posted on    December-26-2014 10:29 PM

 .NET .NET 
Ratings:


 1 Reply(s)
 1110  View(s)
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



Allen Scott

Total Post:41

Points:289
Posted on    December-26-2014 10:40 PM

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
    }
}

Don't want to miss updates? Please click the below button!

Follow MindStick