C# Response.TransmitFile未下载,并且未引发任何错误

C# Response.TransmitFile未下载,并且未引发任何错误,c#,httpresponse,text-files,transmitfile,response.transmitfile,C#,Httpresponse,Text Files,Transmitfile,Response.transmitfile,我目前正在使用HttpResponse从我的服务器下载文件。我已经有几个函数被用来下载Excel/Word文件,但是我在下载我的简单文本文件(.txt)时遇到了麻烦 对于文本文件,我基本上是将文本框的内容转储到一个文件中,尝试使用HttpResponse下载该文件,然后删除临时文本文件 下面是一个适用于Excel/Word文档的代码示例: protected void linkInstructions_Click(object sender, EventArgs e) { String

我目前正在使用HttpResponse从我的服务器下载文件。我已经有几个函数被用来下载Excel/Word文件,但是我在下载我的简单文本文件(.txt)时遇到了麻烦

对于文本文件,我基本上是将文本框的内容转储到一个文件中,尝试使用HttpResponse下载该文件,然后删除临时文本文件

下面是一个适用于Excel/Word文档的代码示例:

protected void linkInstructions_Click(object sender, EventArgs e)
{
    String FileName = "BulkAdd_Instructions.doc";
    String FilePath = Server.MapPath("~/TempFiles/BulkAdd_Instructions.doc");
    System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
    response.ClearContent();
    response.Clear();
    response.ContentType = "application/x-unknown";
    response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
    response.TransmitFile(FilePath);
    response.Flush();
    response.End();  
}
这是一段不起作用的代码。
请注意,代码运行时不会抛出任何错误。文件被创建、删除,但从未转储给用户

protected void saveLog(object sender, EventArgs e)
{ 
    string date = DateTime.Now.ToString("MM_dd_yyyy_hhmm");     //  Get Date/Time
    string fileName = "BulkLog_"+ date + ".txt";                //  Stitch File Name + Date/Time
    string logText = errorLog.Text;                             //  Get Text from TextBox
    string halfPath = "~/TempFiles/" + fileName;                //  Add File Name to Path
    string mappedPath = Server.MapPath(halfPath);               //  Create Full Path

    File.WriteAllText(mappedPath, logText);                     //  Write All Text to File

    System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
    response.ClearContent();
    response.Clear();
    response.ContentType = "text/plain";
    response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
    response.TransmitFile(mappedPath);                //  Transmit File
    response.Flush();

    System.IO.File.Delete(mappedPath);                //  Delete Temporary Log
    response.End();
}

这是因为您在文件发送之前删除了该文件

从MSDN-

将所有当前缓冲的输出发送到 客户端停止执行 页,并引发EndRequest事件

试着把你的System.IO.File.Delete(mappedPath)放进去;响应后的行。End();在我当时的测试中,它似乎起了作用

另外,最好先检查文件是否存在,看不到任何文件。存在于其中,不希望出现任何空引用异常,并设置内容长度

编辑:这是我不久前在一个工作项目中使用的代码,可能会对您有所帮助

// Get the physical Path of the file
string filepath = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + folder + filename;

// Create New instance of FileInfo class to get the properties of the file being downloaded
FileInfo file = new FileInfo(filepath);

// Checking if file exists
if (file.Exists)
{                            
    // Clear the content of the response
    Response.ClearContent();

    // LINE1: Add the file name and attachment, which will force the open/cance/save dialog to show, to the header
    Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}", file.Name));

    // Add the file size into the response header
    Response.AddHeader("Content-Length", file.Length.ToString());

    // Set the ContentType
    Response.ContentType = ReturnFiletype(file.Extension.ToLower());

    // Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use WriteFile instead)
    Response.TransmitFile(file.FullName);

    // End the response
    Response.End();

    //send statistics to the class
}
这是我使用的文件类型方法

//return the filetype to tell the browser. 
//defaults to "application/octet-stream" if it cant find a match, as this works for all file types.
public static string ReturnFiletype(string fileExtension)
{
    switch (fileExtension)
    {
        case ".htm":
        case ".html":
        case ".log":
            return "text/HTML";
        case ".txt":
            return "text/plain";
        case ".doc":
            return "application/ms-word";
        case ".tiff":
        case ".tif":
            return "image/tiff";
        case ".asf":
            return "video/x-ms-asf";
        case ".avi":
            return "video/avi";
        case ".zip":
            return "application/zip";
        case ".xls":
        case ".csv":
            return "application/vnd.ms-excel";
        case ".gif":
            return "image/gif";
        case ".jpg":
        case "jpeg":
            return "image/jpeg";
        case ".bmp":
            return "image/bmp";
        case ".wav":
            return "audio/wav";
        case ".mp3":
            return "audio/mpeg3";
        case ".mpg":
        case "mpeg":
            return "video/mpeg";
        case ".rtf":
            return "application/rtf";
        case ".asp":
            return "text/asp";
        case ".pdf":
            return "application/pdf";
        case ".fdf":
            return "application/vnd.fdf";
        case ".ppt":
            return "application/mspowerpoint";
        case ".dwg":
            return "image/vnd.dwg";
        case ".msg":
            return "application/msoutlook";
        case ".xml":
        case ".sdxl":
            return "application/xml";
        case ".xdp":
            return "application/vnd.adobe.xdp+xml";
        default:
            return "application/octet-stream";
    }
}

最后我自己解决了这个问题。事实证明,这是一个Ajax问题,不允许我的按钮正确回发。这阻止了发射传输文件


谢谢你的帮助

感谢您跟进您的问题所在。我花了好几个小时试图弄清楚为什么尽管没有发生任何事情,但没有抛出错误代码。原来是我的AJAX UpdatePanel神秘而隐蔽地挡住了我的去路。

还可以尝试在客户端保存文本(现在仅限Chrome),而不必往返服务器


是另一个基于flash的…

我在搜索中偶然发现了这篇文章,并注意到它在告诉我们为什么UpdatePanel首先导致了这个问题时没有用

UpdatePanel是异步回发,Response.TransmitFile需要完整回发才能正常工作

触发异步回发的控件需要在UpdatePanel中成为触发器:

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

我解决了这个问题。响应对象需要完全回发才能下载服务器上生成的Excel文件。。但是我的webform上的UpdatePanel(包含我的导出按钮)阻止了完整的回发。所以在UpdatePanel标记中,我更改了这个

<asp:AsyncPostBackTrigger ControlID="btnExport" EventName="Click" />

…为解决此问题,请执行以下操作:

<asp:PostBackTrigger ControlID="btnExport"/>


不幸的是,我最初也尝试过这种方法。在我的例子中,在response.End()下面移动删除行时,它完全跳过删除行,在response.End()处中断。我也尝试过完全删除删除行,但仍然没有成功。你是如何解决的?我有完全相同的问题。我的ModalPopupXtender/UpdatePanel阻止启动文件下载的按钮工作。当我将该按钮移到我的ModalPopupXtender/updatepanel之外时,它可以完美地工作。感谢您让我们知道您修复了它,而不是帮助我们如何修复。告诉我们您如何修复它会像其他人一样好,请修改以解释如何-这是Stackoverflow如何为我们大家工作的!这绝对是解决方案Hi Gopi Rajaseharan,欢迎来到SO。您的答案与2016年9月Josh Harris的答案非常相似。请只添加与其他答案不同的答案。可以,谢谢。