赫赫南仲:c#判断文件类型(转贴)

来源:百度文库 编辑:九乡新闻网 时间:2024/04/29 02:05:32
判断文件类型(文件的真正类型,不是根据扩展名判断),通过文件头来判断
   bool xx=false; //default sFileName is not Exe or Dll File
   System.IO.FileStream fs=new System.IO.FileStream(sFileName,System.IO.FileMode.Open,System.IO.FileAccess.Read);
   System.IO.BinaryReader r=new System.IO.BinaryReader(fs);
   string bx="";
   byte buffer;
   try
   {
   buffer=r.ReadByte();
   bx=buffer.ToString();
   buffer=r.ReadByte();
   bx+=buffer.ToString();
  
   }
   catch (Exception exc)
   {
   Console.WriteLine(exc.Message);
   }
   r.Close();
   fs.Close();
   if (bx=="7790"||bx=="8297"||bx=="8075")//7790:exe,8297:rar,8075:pk
   {
   xx=true;
   }
   Console.WriteLine(bx);
   return xx; dll:MZ
   exe:MZ
   rar:Rar
   zip:PK
  说明:找这篇文章是为了判断文件是不是可执行文件(com、exe、dll、bat)。实际测试的时候,发现com、exe、dll的bx值都是7790,但是bat的值不固定。另,zip是8075,rar是8297