1

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";

    }
Saif AL-Qiari
  • 469
  • 5
  • 20

2 Answers2

3

Try this:

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

public bool IsPdf(string sourceFilePath)
{
  var bytes = System.IO.File.ReadAllBytes(sourceFilePath);
  var match = System.Text.Encoding.UTF8.GetBytes("%PDF-");
  return match.SequenceEqual(bytes.Take(match.Length));
}

Updated as per @Darek's and @Andrew's suggestion.

Avijit
  • 1,219
  • 2
  • 15
  • 28
  • It still lets anyone upload a non-PDF file, just by changing the extension. – Darek Dec 26 '14 at 22:54
  • it does not accept any other file format because the if else statement stop that and also the database only accept pdf file..look to sql query – Saif AL-Qiari Dec 26 '14 at 22:59
  • I still can take a JPEG and upload it as PDF, right? – Darek Dec 26 '14 at 23:02
  • Yes it is possible. Once need to check `MIME type` of the file. See here [`mime type checking`](http://stackoverflow.com/questions/58510/using-net-how-can-you-find-the-mime-type-of-a-file-based-on-the-file-signature/9435701#9435701) – Avijit Dec 26 '14 at 23:05
  • 1
    And if my client would send you JPEG as application/pdf, what would happen? – Darek Dec 26 '14 at 23:06
  • 2
    In other words, this does not check the file format, only the file extension. Even if it were to check the mime type, it would not be checking the file format. It would be a good idea to make sure of what the true requirement is. In particular, if someone took an .exe file, renamed it to .pdf and set the mime type to application/pdf, would anyone be fired if that file got into the database? Would anyone lose money? Would anyone die? – John Saunders Dec 26 '14 at 23:35
  • Updated as per @Darek's and Andrew's suggestion. – Avijit Dec 27 '14 at 21:19
  • @Darek: You deserved that. – Avijit Dec 27 '14 at 22:29
2

Here is one way to find out if at least the file has a PDF header:

var bytes = File.ReadAllBytes(someFileNameHere);
var match = Encoding.UTF8.GetBytes("%PDF-");
var isPDF = match.SequenceEqual(bytes.Take(match.Length));
Darek
  • 4,687
  • 31
  • 47