从byte []返回文件下载

str*_*oir 3 asp.net character-encoding asp.net-mvc-4

这段代码

string xml = XmlHelper.ToXml(queryTemplate);

byte[] xmlb = StringHelper.GetBytes(xml);

var cd = new System.Net.Mime.ContentDisposition
{
    // for example foo.bak
    FileName = String.Format("{0}_v{1}.xml", queryModel.Name, queryModel.Version),

    // always prompt the user for downloading, set to true if you want
    // the browser to try to show the file inline
    Inline = false,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(xmlb, "application/xml");
Run Code Online (Sandbox Code Playgroud)

转换成字符串后,字符串编码不正确 byte[]

所以我需要string立即将文件放入文件中,就像这样

FileStream xfile = new FileStream(Path.Combine(dldir, filename), FileMode.Create, System.IO.FileAccess.Write);
hssfwb.Write(xfile);
Run Code Online (Sandbox Code Playgroud)

但我不想这样做,下载后我不需要该文件.我只需要将其作为文件下载返回到浏览器,并且不希望以后处理文件删除,当有很多请求时,这可能变得非常繁忙.

如何从正确的字符编码string,以byte[]正确地将其返回到浏览器?

GetBytes功能看起来像这样

public static byte[] GetBytes(string str)
{
    byte[] bytes = new byte[str.Length * sizeof(char)];
    System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
    return bytes;
}
Run Code Online (Sandbox Code Playgroud)

Kev*_*cks 14

像这样的东西会起作用:

try
{
    Response.ContentType = "application/octet-stream"; 
    Response.AddHeader( "Content-Disposition", "attachment; filename=" + filename ); 
    Response.OutputStream.Write(xmlb, 0, xmlb.Length); 
    Response.Flush(); 
} 
catch(Exception ex) 
{
    // An error occurred.. 
}
Run Code Online (Sandbox Code Playgroud)