C# 取真实的文件类型
作者:C/S框架网  发布日期:2013/07/31 16:11:03
  C# 取真实的文件类型




C# Code:

public class TrueFileFormat
{
   /// <summary>
   /// 取真实的文件类型
   /// </summary>
   /// <param name="path"></param>
   /// <returns></returns>
   public static FileExtension GetExtension(string path)
   {
      FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);
      BinaryReader r = new BinaryReader(fs);
      string bx = "";
      byte buffer;
      try
      {
         buffer = r.ReadByte();
         bx = buffer.ToString();
         buffer = r.ReadByte();
         bx = buffer.ToString();
         r.Close();
         fs.Close();
         return (FileExtension)int.Parse(bx);//真实的文件类型
      }
      catch
      {
         return FileExtension.UNKNOW;
      }
   }
}

//来源:C/S框架网(www.csframework.com) QQ:1980854898



C# Code:

/// <summary>
/// 文件扩展名编号
/// </summary>
public enum FileExtension
{
   UNKNOW = 0,//未知类型
   JPG = 255216,
   GIF = 7173,
   BMP = 6677,
   PNG = 13780,
   COM = 7790,
   EXE = 7790,
   DLL = 7790,
   RAR = 8297,
   ZIP = 8075,
   XML = 6063,
   HTML = 6033,
   ASPX = 239187,
   CS = 117115,
   JS = 119105,
   TXT = 210187,
   SQL = 255254,
   BAT = 64101,
   BTSEED = 10056,
   RDP = 255254,
   PSD = 5666,
   PDF = 3780,
   CHM = 7384,
   LOG = 70105,
   REG = 8269,
   HLP = 6395,
   DOC = 208207,
   XLS = 208207,
   DOCX = 208207,
   XLSX = 208207,
}

//来源:C/S框架网(www.csframework.com) QQ:1980854898



测试案例:


C# Code:

FileExtension ext = TrueFileFormat.GetExtension(txtFile.Text);
if (ext != FileExtension.XLS)
{
   Msg.Warning("无效的Excel文件!");
   e.Cancel = true;
}

//来源:C/S框架网(www.csframework.com) QQ:1980854898


上一篇 下一篇