判断文件真实的类型,不是通过扩展名来判断:而是通过byte[]数组前两位编码来判断,
原文连接 https://www.cnblogs.com/Percy_Lee/p/4980451.html
/// <summary> /// 判断文件格式 /// http://www.cnblogs.com/babycool /// </summary> /// <param name="filePath"></param> /// <returns></returns> public static bool IsAllowedExtension(string filePath) {FileStream stream </span>= <span style="color: #0000ff;">new</span><span style="color: #000000;"> FileStream(filePath, FileMode.Open, FileAccess.Read); BinaryReader reader </span>= <span style="color: #0000ff;">new</span><span style="color: #000000;"> BinaryReader(stream); </span><span style="color: #0000ff;">string</span> fileclass = <span style="color: #800000;">""</span><span style="color: #000000;">; </span><span style="color: #008000;">//</span><span style="color: #008000;"> byte buffer;</span> <span style="color: #0000ff;">try</span><span style="color: #000000;"> { </span><span style="color: #008000;">//</span><span style="color: #008000;">buffer = reader.ReadByte(); </span><span style="color: #008000;">//</span><span style="color: #008000;">fileclass = buffer.ToString(); </span><span style="color: #008000;">//</span><span style="color: #008000;">buffer = reader.ReadByte(); </span><span style="color: #008000;">//</span><span style="color: #008000;">fileclass += buffer.ToString();</span> <span style="color: #0000ff;">for</span> (<span style="color: #0000ff;">int</span> i = <span style="color: #800080;">0</span>; i < <span style="color: #800080;">2</span>; i++<span style="color: #000000;">) { fileclass </span>+=<span style="color: #000000;"> reader.ReadByte().ToString(); } } </span><span style="color: #0000ff;">catch</span><span style="color: #000000;"> (Exception) { </span><span style="color: #0000ff;">throw</span><span style="color: #000000;">; } </span><span style="color: #0000ff;">if</span> (fileclass == <span style="color: #800000;">"</span><span style="color: #800000;">255216</span><span style="color: #800000;">"</span><span style="color: #000000;">) { </span><span style="color: #0000ff;">return</span> <span style="color: #0000ff;">true</span><span style="color: #000000;">; } </span><span style="color: #0000ff;">else</span><span style="color: #000000;"> { </span><span style="color: #0000ff;">return</span> <span style="color: #0000ff;">false</span><span style="color: #000000;">; } </span><span style="color: #008000;">/*</span><span style="color: #008000;">文件扩展名说明 * 255216 jpg * 208207 doc xls ppt wps * 8075 docx pptx xlsx zip * 5150 txt * 8297 rar * 7790 exe * 3780 pdf * * 4946/104116 txt * 7173 gif * 255216 jpg * 13780 png * 6677 bmp * 239187 txt,aspx,asp,sql * 208207 xls.doc.ppt * 6063 xml * 6033 htm,html * 4742 js * 8075 xlsx,zip,pptx,mmap,zip * 8297 rar * 01 accdb,mdb * 7790 exe,dll * 5666 psd * 255254 rdp * 10056 bt种子 * 64101 bat * 4059 sgf </span><span style="color: #008000;">*/</span><span style="color: #000000;"> }</span></pre>