文档和视频文件格式的后缀名验证以及图片的真实验证帮助类
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace Reform.FolderManage.Cls { public class FileHelper { /// <summary> /// 图片类型头部编码 /// </summary> public enum ImgExtension { JPG = 255216, GIF = 7173, BMP = 6677, PNG = 13780 } /// <summary> /// 文件类型的判断 /// </summary> /// <param name="fileName">文件</param> /// <param name="fileType">文件类型</param> /// <returns></returns> public static bool IsRealFile(string fileName, string fileType) { string fileExt = Path.GetExtension(fileName).ToLower();//取得文件后缀名 if (fileType == "图片") { if (IsAllowedExtension(fileName)) return true; } if (fileType == "视频") { List<string> list = new List<string>(); list.Add(".flv"); list.Add(".wmv"); list.Add(".avi"); list.Add(".3gp"); Path.GetExtension(fileName).ToLower();//取得文件后缀名 return IsExistEx(list, fileExt); } if (fileType == "文档") { List<string> list = new List<string>(); list.Add(".doc"); list.Add(".pdf"); return IsExistEx(list, fileExt); } return false; } /// <summary> /// 判断文件后缀 /// </summary> private static bool IsExistEx(List<string> list, string fileExt) { if (list.Contains(fileExt))//在列表中 { return true; } return false; } #region 图片处理 /// <summary> /// 是否是真实的图片类型 /// </summary> public static bool IsAllowedExtension(string imgFileName) { System.IO.FileStream fs = new System.IO.FileStream(imgFileName, System.IO.FileMode.Open, System.IO.FileAccess.Read); System.IO.BinaryReader br = new System.IO.BinaryReader(fs); string fileclass = ""; byte buffer; try { buffer = br.ReadByte(); fileclass = buffer.ToString(); buffer = br.ReadByte(); fileclass += buffer.ToString(); } catch { } br.Close(); fs.Close(); ImgExtension[] fileEx = { ImgExtension.BMP, ImgExtension.GIF, ImgExtension.JPG, ImgExtension.PNG }; foreach (ImgExtension fe in fileEx) { if (Int32.Parse(fileclass) == (int)fe) return true; } return false; } #endregion } }
念念不忘,必有回响。技术成就梦想!