打开读取文件,根据文件的位长判断文件的类型:

//判断上传文件的真正类型
private bool IsAllowedExtension(FileUpload hifile)
{
string fullPath = System.IO.Path.GetFullPath(FileUploadImg.PostedFile.FileName); //获取文件的绝对路径
System.IO.FileStream fs = new System.IO.FileStream(fullPath, 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 == "13780")//说明255216是jpg;7173是gif;6677是BMP,13780是PNG;7790是exe,8297是rar
{
return true;
}
else
{
return false;
}
}
网友评论