根据文件名判断文件扩展名 和 根据流真正判断文件类型的关键函数

/// <summary>
   /// 根据文件名判断文件扩展名 和 根据流真正判断文件类型的关键函数
   /// </summary>
   /// <param name="thefile">上传的文件</param>
   /// <returns>true - 允许上传的文件类型 false-不允许</returns>
   public static bool CheckUploadImgExtension(System.Web.HttpPostedFile thefile)
   {
    //取得文件的扩展名,并转换成小写
    string fileExtension = System.IO.Path.GetExtension( thefile.FileName).ToLower();

    //限定只能上传jpg和gif图片
    string[] allowExtension = { ".jpg", ".gif", ".bmp" };

    bool fileOk = false;
    //对上传的文件的类型进行一个个匹对
    for (int i = 0; i < allowExtension.Length; i++)
    {
     if (fileExtension == allowExtension[i])
     {
      fileOk = true;

      System.IO.BinaryReader reader = new System.IO.BinaryReader( thefile.InputStream );
      string fileclass = "";
      byte buffer;
      try
      {
       buffer = reader.ReadByte();
       fileclass = buffer.ToString();
       buffer = reader.ReadByte();
       fileclass += buffer.ToString();
      }
      catch
      {
       fileOk = false;
      }
      reader.Close();

      //说明 255216 是jpg; 7173 是gif; 6677 是BMP, 13780是PNG; 7790 是exe, 8297 是rar
      if (fileclass == "255216" || fileclass == "7173" || fileclass == "6677")
      {
       fileOk = true;
      }
      else
      {
       fileOk = false;
      }

      break;
     }
    }

    return fileOk;
   }

原文地址:https://www.cnblogs.com/appleseed/p/1247828.html