【问题标题】:c# check the extension of the uploaded filec#检查上传文件的扩展名
【发布时间】:2017-07-28 14:30:46
【问题描述】:

我正在寻找一种简单的方法来检查上传文件的扩展名,如果是 PDF 文件,请执行某些操作,否则会显示一条警告消息(错误的文件类型),但我的代码的问题是如果我选择了任何文件类型而不是 PDF,它将显示带有此消息的错误页面:

   Server Error in '/' Application.
   PDF header signature not found.
   Exception Details: iTextSharp.text.exceptions.InvalidPdfException: PDF header signature not found.



        <asp:FileUpload runat="server" ID="file1" AllowMultiple="true" />


        string fileName = Path.GetFileName(file1.FileName);
        FileInfo fi = new FileInfo(fileName);
        string ext = fi.Extension;

        if (ext == ".pdf")
        {
        //do something
        }
        else
        Label1.Text = string.Format("wrong file type");

【问题讨论】:

标签: c# pdf


【解决方案1】:

获取上传文件的文件名

string FileName = file1.PostedFile.FileName;

获取上传文件的扩展名

string FileExtension = System.IO.Path.GetExtension(file1.PostedFile.FileName);

【讨论】:

    【解决方案2】:
     bool isValidFile = false;
    
                string[] validFileTypes = { "xlsx", "xls", "pdf" };
                string ext = Path.GetExtension(File_Uploader.PostedFile.FileName);
    
                for (int i = 0; i < validFileTypes.Length; i++)
                {
                    if (ext == "." + validFileTypes[i])
                    {
                        isValidFile = true;
                        break;
                    }
                }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-28
      • 1970-01-01
      • 2019-12-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多