I recently posted a question asking how I can return a File from a byte[] that I am storing.
The question is here byte[] to File Type in MVC 3
Just for reference, I have resulted to storing the binary for the file as a string.
When I return the document, I am calling the following code:
var data = document.BinData.ToByteArray();
return File(data, document.MIMEType,document.Extension);
where BinData is a string, and ToByteArray() is an extension method I wrote:
public static byte[] ToByteArray(this string data)
{
byte[] binData= new byte[data.Length];
for (var i = 0; i < data.Length; i++)
{
binData[i] = (byte)data[i];
}
return binData;
}
The problem I am experiencing is, when I get the file back, I am getting something like the following:

Is there anything you can see that I am doing incorrectly?
Edit, I have changed the following “Upload” code to the following:
var stream = BinData.InputStream;
byte[] data = new byte[BinData.ContentLength];
stream.Read(data, 0, BinData.ContentLength);
string documentData = Convert.ToBase64String(data);
where documentData is the string I am storing:
and the download code is the following:
var data = Convert.FromBase64String(document.BinData);
return File(data,document.MimeType,document.Title + document.Extension);
where document.BinData is the documentData from above
I would wager that the problem is in the line:
Based on your decoder (
ToByteArray), this is not really encoded in a suitable way; note; you cannot treat arbitrary binary data as a string (at least, not in the way you are trying). The preferred way to do this is simply:(although several other approaches – for example hex – would work too)
This should give you back the correct
byte[], and all should be good from there.Re your
Stream.Readcode, and assuming you already have some kind of oversized length check to prevent from DDOS, note that you should loop onRead: