我正在寻找一种简单的方法来检查上传文件的扩展名,如果是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");
答案 0 :(得分:4)
获取上传文件的FileName
string FileName = file1.PostedFile.FileName;
获取上传文件的扩展程序
string FileExtension = System.IO.Path.GetExtension(file1.PostedFile.FileName);
答案 1 :(得分:1)
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;
}
}