Asp.net 返回从字节[]下载的文件

Asp.net 返回从字节[]下载的文件,asp.net,character-encoding,asp.net-mvc-4,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

此代码

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");
将字符串编码转换为
字节[]

所以我需要立即将
字符串
放入文件,如下所示

FileStream xfile = new FileStream(Path.Combine(dldir, filename), FileMode.Create, System.IO.FileAccess.Write);
hssfwb.Write(xfile);
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;
}
但我不想这样做,我不需要下载后的文件。我只需要将其作为文件下载返回到浏览器,不想在下载后处理文件删除,当有很多请求时,这会变得非常繁忙

如何将字符编码从
string
更正为
byte[]
并将其正确返回到浏览器

GetBytes
函数如下所示

FileStream xfile = new FileStream(Path.Combine(dldir, filename), FileMode.Create, System.IO.FileAccess.Write);
hssfwb.Write(xfile);
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;
}

类似这样的方法会奏效:

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.. 
}
在这种情况下:

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;
}
最终将使用UTF-16LE编码,因为这就是
char
数组的内部结构

您应该去掉该函数,因为它是现成功能的误导性和冗余复制,因为
System.Text.Encoding.Unicode.GetBytes
已经做了同样的事情:使用小端字节顺序对UTF-16格式进行编码

如果在不指定编码的情况下创建临时文件有效,则可能需要Windows-1252,因为在创建文件时很可能会隐式使用该文件:

Encoding enc = Encoding.GetEncoding(1252);
byte[] xmlb = enc.GetBytes(xml);
如果您想要UTF-8,您可以:

byte[] xmlb = Encoding.UTF8.GetBytes(xml);

我已经找到了答案,原来问题是字符编码

下面是解决方案链接


什么是
StringHelper
,在没有指定编码的情况下对字符串调用类似
GetBytes
的东西是没有意义的对不起,没有包含GetBytes函数,我已经编辑了这个问题