三、可以实现真正意义上的文件类型判断

    try
                {
                    //判断是否已经选取文件
                    if (FileUpload1.HasFile)
                    {
                        if (IsAllowedExtension(FileUpload1))
                        {
                            string path = Server.MapPath("~/images/");
                            FileUpload1.PostedFile.SaveAs(path + FileUpload1.FileName);
                            Response.Write("<script>alert('上传成功');</script>");
                        }
                        else
                        {
                            Response.Write("<script>alert('您只能上传jpg或者gif图片');</script>");
                        }
     
                    }
                    else
                    {
                        Response.Write("<script>alert('你还没有选择文件');</script>");
                    }
                }
                catch (Exception error)
                {
                    Response.Write(error.ToString());
                }
                #endregion
            }
    //真正判断文件类型的关键函数
            public static bool IsAllowedExtension(FileUpload hifile)
            {
                System.IO.FileStream fs = new System.IO.FileStream(hifile.PostedFile.FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                System.IO.BinaryReader r = new System.IO.BinaryReader(fs);
                string fileclass = "";
                //这里的位长要具体判断.
                byte buffer;
                try
                {
                    buffer = r.ReadByte();
                    fileclass = buffer.ToString();
                    buffer = r.ReadByte();
                    fileclass += buffer.ToString();
     
                }
                catch
                {
     
                }
                r.Close();
                fs.Close();
                if (fileclass == "255216" || fileclass == "7173")//说明255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar
                {
                    return true;
                }
                else
                {
                    return false;
                }
     
            }