ASP.NET MVC-检查上传的文件是.EXE还是PDF文件

时间:2019-06-25 17:41:43

标签: c# asp.net-mvc file-upload

考虑到该代码,我如何检查用户要上传的文件是否具有.EXE文件或.PDF,例如

  [HttpPost]
    public JsonResult SaveInfo()
    {
        try
        {
            var model = JsonConvert.DeserializeObject<ApontamentoViewModel>(Request.Form["model"]);
            if (!string.IsNullOrWhiteSpace(model.filePath))
            {
                //convert to list
                var listArquivos = model.CaminhoArquivo.Split(';').Distinct().ToList();

                //for each file in the list, move from temporary folder to final folder
                model.filePath= string.Join(";", listArquivos);


                string caminhoRaiz = Server.MapPath(System.Configuration.ConfigurationManager.AppSettings.Get("FinalUploadFolder"));
                _CaminhoRaizTempUpload = Server.MapPath(System.Configuration.ConfigurationManager.AppSettings.Get("TempUploadFolder"));

                var files = Directory.EnumerateFiles(_CaminhoRaizTempUpload, "*.*", SearchOption.AllDirectories)
                                 .Where(s => listArquivos.Any(arquivo => s.Contains(arquivo)))
                                 .ToList();


                files.ForEach(arquivoMover =>
                {
                    var nomeArquivo = System.IO.Path.GetFileName(arquivoMover);
                    System.IO.File.Move(arquivoMover, System.IO.Path.Combine(caminhoRaiz, nomeArquivo));

                });

            }

1 个答案:

答案 0 :(得分:0)

您可以使用

System.IO.Path.GetExtension(FileName);

用于提取文件扩展名,并按如下所示使用它:

files.ForEach(arquivoMover =>
            {
                var nomeArquivo = System.IO.Path.GetFileName(arquivoMover);
                var fileExt = System.IO.Path.GetExtension(arquivoMover);
                if(fileExt==".EXE")
                { 
                    //is a .EXE file 
                }
                System.IO.File.Move(arquivoMover, System.IO.Path.Combine(caminhoRaiz, nomeArquivo));

            });

此外,您可以使用传统的字符串函数从文件名中获取最后4个字符:

string fileExt = nomeArquivo.Substring((nomeArquivo.Length - 4), 4);

fileExt = fileExt.ToLower();
if(fileExt == ".exe")
  do_things_for_exe();
else if(fileExt == ".pdf")
  do_things_for_pdf();
else:
  throw new Exception("file format unrecognized");