校验文件类型是否在白名单内。
作者:互联网
class Program { static void Main(string[] args) { using (var Stream = new FileStream(@"C:\Users\qa_weiwa\Downloads\core 6.0.exe", FileMode.Open)) { var inspector = new FileFormatInspector(); var rt = FileExtensionValid.IsValid(inspector, Stream); if (rt.Item1) { Console.WriteLine("附件类型符合要求"); } else { Console.WriteLine(rt.Item2); } Console.ReadKey(); } } public static class FileExtensionValid { /// <summary> /// 校验文件类型是否在白名单内。 /// 白名单:jpg、png、tif、gif、zip、pdf、doc、docx、xls、xlsx、msg /// </summary> /// <param name="fileFormatInspector"></param> /// <param name="stream"></param> /// <returns></returns> public static Tuple<bool, string> IsValid(FileFormatInspector fileFormatInspector,Stream stream) { var format = fileFormatInspector.DetermineFileFormat(stream); return FileExtensionIsInWhiteList(format); } private static Tuple<bool, string> FileExtensionIsInWhiteList(FileFormat fileFormat) { // Jpeg if (fileFormat is null || fileFormat is Jpeg || fileFormat is Png || fileFormat is Tiff || fileFormat is Gif || fileFormat is Gif || fileFormat is Zip || fileFormat is Pdf || fileFormat is Word || fileFormat is Excel || fileFormat is OutlookMessage ) { return new Tuple<bool, string>(true, ""); } else { return new Tuple<bool, string>(false, "上传的文件类型不正确,请上传jpg、png、tif、gif、zip、pdf、doc、docx、xls、xlsx、msg类型的附件"); } } } }
标签:Console,Tuple,校验文件,var,类型,static,白名单,new,fileFormat 来源: https://www.cnblogs.com/Insist-Y/p/16650936.html