c# - TransmitFile 缺少文件末尾的单个字节

标签 c# asp.net transmitfile

传递的参数是:

`C:\Licenses\testfolder\PERSONAL-Wednesday 04 July-0405.txt`,`c2license.txt`

函数是:

/// <summary>
/// Starts serving the download
/// </summary>
public static void InitStoreDownload(string filePath, string serveFileName)
{
    // Get size of file
    var f = new FileInfo(filePath);

    var fileSize = f.Length;
    var extension = f.Extension;

    var context = HttpContext.Current;

    context.Response.Clear();
    context.Response.Buffer = false;

    // Correct mime type
    if (extension.Equals(".zip", StringComparison.CurrentCultureIgnoreCase))
        context.Response.ContentType = "application/octet-stream";
    else if (extension.Equals(".txt", StringComparison.CurrentCultureIgnoreCase))
    {
        context.Response.ContentType = "text/plain";
    }

    context.Response.AddHeader("Content-Disposition", "attachment; filename=" + serveFileName);
    context.Response.AddHeader("Content-Length", fileSize.ToString());
    context.Response.TransmitFile(filePath);
    context.Response.Close();

    context.Response.End();
}

服务器上的 C:\Licenses\testfolder\PERSONAL-Wednesday 04 July-0405.txt 文件长 475 字节。

使用此脚本获取时下载的文件为 474 字节,文件末尾缺少一个字节。 (最后一个字节是句号,存在于服务器上的文件中,但通过此函数下载时不存在)。这会导致文件无效。

我们正在绞尽脑汁想弄清楚为什么会丢失一个字节,有人能帮忙吗?

最佳答案

尝试使用

Response.TransmitFile(filePath);
HttpContext.Current.ApplicationInstance.CompleteRequest(); 

代替

Response.Close();
Response.End();

或者像其他提到的那样:

Close() 之前调用 Flush()

Response.TransmitFile(filePath);
Response.Flush();
Response.Close();
Response.End();

或省略 Close() 的调用并直接调用 End(),因为它包括刷新 Response。

Response.TransmitFile(filePath);
Response.End();

有一个 thread关于 Response.End() 可能包含对您有用的信息。

关于c# - TransmitFile 缺少文件末尾的单个字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11330076/

相关文章:

C# 多态性 - 为什么以及何时

.net - 如何创建GUID?

c# - CSS 类不能应用于 ASPX C# View 引擎上的 EditorFor

asp.net - 包含 '+' 的 Request.QueryString[]

c++ - 与其他方法相比,为什么我对 TransmitFile 的调用性能不佳?

c# - 如何使用 C# 复制 MySql 数据库架构?

c# - 将最小级别记录到日志文件

c# - Entity Framework - 'providerInvariantName' 参数需要非空字符串