判断文件类型

判断文件类型(文件的真正类型,不是根据扩展名判断),通过文件头来判断

文件类型枚举参数代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ServiceContract
{
    public class FileExtension
    {
        public enum FileExtensions
        {
            JPG = 255216,
            GIF = 7173,
            PNG = 13780,
            SWF = 6787,
            RAR = 8297,
            ZIP = 8075,
            _7Z = 55122,
            VALIDFILE = 9999999
            // 255216 jpg;         
            // 7173 gif;          
            // 6677 bmp,       
            // 13780 png;       
            // 6787 swf         
            // 7790 exe dll,         
            // 8297 rar       
            // 8075 zip     
            // 55122 7z      
            // 6063 xml       
            // 6033 html     
            // 239187 aspx      
            // 117115 cs         
            // 119105 js         
            // 102100 txt        
            // 255254 sql   
        }
    }
}

文件调用方法如下:

 /// <summary>
        /// 判断文件类型
        /// </summary>
        /// <param name="sFileName">文件路径</param>
        /// <returns>检查状态 false不是正确的ZIP包,true 是正确的ZIP包</returns>
        private bool FileExtensions(string sFileName)
        {
            bool type = false;
            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();
                if (bx == FileExtension.FileExtensions.ZIP.GetHashCode().ToString())
                {
                   // MessageBox.Show("是ZIP包");
                    type = true;
                }
                else
                {
                    MessageBox.Show("当前的文件不是正确的ZIP包,

可能有以下原因:

1、压缩格式不对。

2、直接将文件后缀名改为.zip", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);  
                   
                }

            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message);
            }
            return type;
        }
原文地址:https://www.cnblogs.com/happygx/p/3277897.html