strike_noir strike_noir - 5 months ago 50
ASP.NET (C#) Question

Return file download from byte[]

This code

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");

Turns out the string encoding is incorrect after it's converted into

So I need to put the
immediately into file, like this

FileStream xfile = new FileStream(Path.Combine(dldir, filename), FileMode.Create, System.IO.FileAccess.Write);

But I don't want to do this, I don't need the file after the download. I just need to return it to the browser as file download and don't want to have to deal with file deletion afterward which can become pretty hectic when there's a lot of request.

How to correct the character encoding from
and correctly return it to the browser?

function looks like this

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;

Answer Source

I have had the answer for this, it turns out the problem was character encoding.

The solution link is below

Converting string to byte[] creates zero character

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download