如何以二进制形式下载 xml 文件?

How to download an xml file in binary?

我有一个link叫下载,他需要在浏览器中下载一个XML数据库中记录的二进制格式的文件。我做错了什么?

遵循以下代码:

 protected void DownloadFile_Click(object sender, EventArgs e)
    {
        int invoiceId = int.Parse((sender as LinkButton).CommandArgument);

        InvoiceManager iv = new InvoiceManager();
        Invoice invoice = iv.Find(invoiceId);
        if (invoice != null)
        {
            byte[] fileInBytes = invoice.FileContent;

            // Send the XML file to the web browser for download.
            Response.Clear();
            Response.Buffer = true;
            Response.ContentType = "text/xml";
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + invoice.FileName);
            Response.BinaryWrite(fileInBytes);
            Response.End();

        }
    }

如果您的意思是它显示在浏览器中而不是提示下载,请尝试将您的 ContentType 从 text/xml 更改为

protected void DownloadFile_Click(object sender, EventArgs e)
{
    int invoiceId = int.Parse((sender as LinkButton).CommandArgument);

    InvoiceManager iv = new InvoiceManager();
    Invoice invoice = iv.Find(invoiceId);
    if (invoice != null)
    {
        byte[] fileInBytes = invoice.FileContent;

        // Send the XML file to the web browser for download.
        Response.Clear();
        Response.Buffer = true;
        Response.ContentType = "application/octet-stream";
        Response.AppendHeader("Content-Disposition", "attachment; filename=" + invoice.FileName);
        Response.BinaryWrite(fileInBytes);
        Response.End();

    }
}

这样你就可以强制浏览器提示下载文件,而不是试图在浏览器中显示它window。