如何检查文件格式

时间:2014-12-26 22:18:03

标签: c# asp.net

允许的文件格式只是PDF文件,如果在继续更新数据库之前上传的文件不是PDF,如何检查文件格式并显示错误消息。以下代码始终显示文件无法识别,即使文件是PDF,也未更新数据库。

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

    }

2 个答案:

答案 0 :(得分:3)

试试这个:

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

按照@Darek和@ Andrew的建议更新。

答案 1 :(得分:2)

以下是查找至少文件是否包含PDF标题的一种方法:

var bytes = File.ReadAllBytes(someFileNameHere);
var match = Encoding.UTF8.GetBytes("%PDF-");
var isPDF = match.SequenceEqual(bytes.Take(match.Length));