c#中无法下载的文件

本文关键字:文件 下载 | 更新日期: 2023-09-27 17:50:55

我正在尝试下载由共享文件夹上的代码生成的文件。文件被创建,当我尝试下载文件的下载代码工作正常,但文件没有下载在任何浏览器上。下载按钮放置在asp.net Update Panel中这是下载代码

try
{
    String contentType = String.Empty;
    FileInfo objFileInfo = null;
    this.FileMode = (DownloadFileMode)Session["FileMode"]; //DownloadFileMode.SingleFile;
    FileServerPath = ConfigurationManager.AppSettings["FileServerPath"];
    if (this.FileMode == DownloadFileMode.SingleFile)
    {
        if (Session["FileName"] != null)
        {
            FileName = Session["FileName"].ToString();
            contentType = "application/octet-stream";
            objFileInfo = new FileInfo(FileServerPath + FileName);
        }
        else
        {
            FileName = Session["SingleFile"].ToString();
            contentType = "application/octet-stream";
            objFileInfo = new FileInfo(FileServerPath + FileName);
        }
    }
    else if (this.FileMode == DownloadFileMode.ZippedFile)
    {
        FilesList = (List<String>)Session["FilesList"];
        contentType = "application/x-zip-compressed";
        if (FilesList.Count == 0)
            throw new Exception("No file to download");
        String strFilePath = String.Empty;
        String strZipPath = String.Empty;
        strZipPath = FileServerPath + "file" + CurrentUserSession.UserId.ToString() + "_" + CurrentUserSession.SessionId.ToString() + "_" + DateTime.Now.ToShortDateString().Replace("/", "-") + ".zip";
        DownloadFiles(strZipPath, FilesList);
        objFileInfo = new FileInfo(strZipPath);
    }
    else
    {
        ScriptManager.RegisterStartupScript(this.Page, typeof(String), "MessageAlert", "alert('Invalid file mode');", true);
    }
    Response.Clear();
    Response.AddHeader("Content-Disposition", "attachment; filename=" + objFileInfo.Name);
    Response.AddHeader("Content-Length", objFileInfo.Length.ToString());
    Response.ContentType = contentType;
    Response.TransmitFile(objFileInfo.FullName);
    //Response.End();
    HttpContext.Current.ApplicationInstance.CompleteRequest();
}
catch(Exception ex)
{
    ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "MessageAlert", "alert('" + ex.Message + "');", false);
}

c#中无法下载的文件

检查此代码。

    long sz = objFileInfo.Length;
    Response.ClearContent();
    Response.AddHeader("Content-Disposition", 
    string.Format("attachment; filename = {0}",System.IO.Path.GetFileName(objFileInfo)));
    Response.AddHeader("Content-Length", sz.ToString("F0"));
    Response.TransmitFile(objFileInfo);
    Response.End();

我认为你需要在你的UpdatePanel中添加以下触发器。

<Triggers>
<asp:PostBackTrigger ControlID="Your_Download_Button_ID">
</Triggers>