在我的项目中,我有一个包含N个文件的文件夹。我需要一个功能,页面应该包含所有这些文件的链接,以便客户端可以下载这些文件。
为此,我动态创建了链接按钮,并使用每个链接按钮链接每个文件。
守则是
string filePath = Request.PhysicalPath.Substring(0, Request.PhysicalPath.LastIndexOf("\\"));
filePath = filePath.Substring(0, filePath.LastIndexOf("\\"));
filePath = filePath.Substring(0, filePath.LastIndexOf("\\")) + "\\Export";
string[] files = System.IO.Directory.GetFiles(filePath);
Array.Sort(files);
Array.Reverse(files);
int counter = 0;
foreach (string file in files)
{
if (counter >= 10)
break;
LinkButton linkButton = new LinkButton();
int startIndex = Convert.ToInt32(file.LastIndexOf("\\"));
int length = Convert.ToInt32(file.Length);
string fileName = file.Substring(startIndex + 1, length - startIndex - 1).ToString();
fileName = fileName.Substring(0, fileName.LastIndexOf("."));
string[] a = fileName.Split('_');
string year = a[1].Substring(0, 4);
string month = a[1].Substring(4, 2);
switch (month)
{
case "01":
month = "January";
break;
case "02":
month = "February";
break;
case "03":
month = "March";
break;
case "04":
month = "April";
break;
case "05":
month = "May";
break;
case "06":
month = "June";
break;
case "07":
month = "July";
break;
case "08":
month = "August";
break;
case "09":
month = "September";
break;
case "10":
month = "October";
break;
case "11":
month = "November";
break;
case "12":
month = "December";
break;
}
counter++;
linkButton.ForeColor = System.Drawing.ColorTranslator.FromHtml("#b32317");
linkButton.Text = month + " " + year + " Car Hire Details";
//hyperlink.NavigateUrl = file.ToString();
linkButton.Font.Bold = true;
//hyperlink.ID = "TestLB";
linkButton.Command += new CommandEventHandler(this.lb_Command);
linkButton.CommandArgument = file.ToString();
Panel1.Controls.Add(linkButton);
Label lbl1 = new Label();
lbl1.Text = "<br /> <br />";
Panel1.Controls.Add(lbl1);
}
}
protected void lb_Command(object sender, CommandEventArgs e)
{
System.String filename = e.CommandArgument.ToString();// this is your file name
Response.ContentType = "Plain/Text";
System.String disHeader = "Attachment; Filename=\"" + filename + "\"";
Response.AppendHeader("Content-Disposition", disHeader);
System.IO.FileInfo fileToDownload = new System.IO.FileInfo(e.CommandArgument.ToString());
//filepath to download
Response.Flush();
Response.WriteFile(fileToDownload.FullName);
}
但问题是,当我试图下载时:
文件正在以HTML格式下载,而且下载文件的文件名与我的代码文件名相同,我想要实际名称。
下载的文件包含实际数据,但它也包含此链接所在页面的html代码
任何身体都可以帮助我。