Byte array not writing to pdf stream c# - c#

I've have a byte array that has all the data needed and can be displayed in a pdf that can be opened if I use this code:
System.IO.File.WriteAllBytes(#"C:\Users\Person\Downloads\results.pdf", bytes)
That let's me know the byte array should be good. The issue is I'm trying to create a pdf on the fly and when I view the call in the network tab in dev tools, it shows a 200 and in the response tab I get a text response. When I copy that response in a text editor and save it as a pdf, it has the correct amount of pages, but no data in it. So I have two issues here. For some reason, it is not being returned as a pdf AND the byte array is not being written to it. Any suggestions on what I can do? I've looked at stack overflow all day and have tried all kinds of things including setting the contentType to application/pdf.
byte[] bytes = ms.ToArray();
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.Buffer = true;
response.AddHeader("Accept-Header", bytes.Length.ToString());
response.AddHeader("Content-Length", bytes.Length.ToString());
response.AddHeader("Content-Disposition", "attachment;filename=Results.pdf");
response.AddHeader("Content-Description", "File Download");
response.ContentType = "application/octet-stream";
response.OutputStream.Write(bytes, 0, onvert.ToInt32(bytes.Length));
//I've tried using this as well
//response.BinaryWrite(bytes);
response.Flush();
response.End();
UPDATED CODE:
byte[] bytes = ms.ToArray();
HttpResponse response = HttpContext.Current.Response;
try
{
response.Clear();
response.ClearHeaders();
response.ClearContent();
response.AddHeader("Accept-Header", bytes.Length.ToString());
response.AddHeader("Content-Length", bytes.Length.ToString());
response.AddHeader("Content-Disposition", "attachment;filename=Results.pdf");
response.ContentType = "application/pdf";
response.BinaryWrite(bytes);
response.Flush();
}
catch { }
finally
{
response.End();
}

I got it working with this:
response.Clear();
response.ClearHeaders();
response.ClearContent();
response.ContentType = "application/pdf";
response.AddHeader("content-disposition", "attachment; filename=Results.pdf");
response.BinaryWrite(bytes);
response.Flush();
response.Close();

Related

Binary to File download - But the downloaded file has no file extension?

protected void getFileAttachment(byte[] bytes)
{
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = fileType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + "test101");
Response.OutputStream.Write(bytes,0,bytes.Length);
Response.BinaryWrite(bytes);
Response.Flush();
}
I'm trying to convert varbinary that is saved in SQL Server and I'm having trouble because the output file has no extension
Response.AppendHeader("Content-Disposition", "attachment; filename=" + "test101.filetype");
My fault - I did not include the file extension in my database
Thanks for the comments!

how to download an excel file from aspx webpage

I am trying to fetch an excel file stored in bytes from database from an aspx webpage and download and open in .xls format, however the file is getting downloaded as .aspx . How to resolve this?
I tried:
private void download(DataTable dt)
{
if (dt.Rows.Count > 0)
{
Byte[] bytes = (Byte[])dt.Rows[0]["xyz"];
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
Response.BinaryWrite(bytes);
// Response.Flush();
Response.End();
}
}
You need to set the Content-Disposition header. For example:
Content-Disposition: attachment; filename=your-excel-file.xlsx
And in code:
Response.AddHeader("Content-Disposition", "attachment; filename=your-excel-file.xlsx");

TransmitFile is not working

I have a file, and it is full path (plus the file name) is in this variable:
fileTemporary
i want to download that file to the client.
i do this:
HttpContext.Current.Response.TransmitFile(fileTemporary);
but nothing happen, i mean when i click the button, this file executes, but nothing is being downloaded to the client. i don't see any file on the browser of the client.
what mistake did i do please?
If you use MVC you can:
[HttpGet]
public virtual ActionResult GetFile(string fileTemporary)
{
// ...preparing file path... init fileTemporary.
var bytes = System.IO.File.ReadAllBytes(fileTemporary);
var fileContent = new FileContentResult(bytes, "binary/octet-stream");
Response.AddHeader("Content-Disposition", "attachment; filename=\"YourFileName.txt\"");
return fileContent;
}
If you use ASP.NET or whatever you can use following (sorry, my old code, but you can understand approach):
var bytes = System.IO.File.ReadAllBytes(fileTemporary);
SendFileBytesToResponse(bytes, fileName);
public static bool SendFileBytesToResponse(byte[] bytes, string sFileName)
{
if (bytes!= null)
{
string downloadName = sFileName;
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.Clear();
response.AddHeader("Content-Type", "binary/octet-stream");
response.AddHeader("Content-Disposition",
"attachment; filename=" + downloadName + "; size=" + bytes.Length.ToString());
response.Flush();
response.BinaryWrite(bytes);
response.Flush();
response.End();
}
return true;
}
Without reingeneering your solution:
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.AddHeader("Content-Type", "binary/octet-stream");
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition",
"attachment; filename=" + fileName);
System.Web.HttpContext.Current.Response.TransmitFile(fileName);
If you would like browser to interpret you file right, you will need to specify header "Content-Type" more precise.
Please see list of content types

How to use Using Response.Transmit()

Here is a piece of my code:
if (objTbl.Rows.Count > 0)
{
string attachment = "attachment; filename=Call-Details-Report-" + startDate.SelectedDate.Value.ToString("MM-dd-yyyy") + ".csv";
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "text/csv";
Response.AddHeader("Pragma", "public");
bool commaRequired = false;
if (this.chkNET_NETWORKID.Checked)
{
Response.Write("Network ID");
commaRequired = true;
}
if (this.chkNET_NETWORKNAME.Checked)
{
if (commaRequired)
{
Response.Write(",");
}
Response.Write("Network");
commaRequired = true;
}
}
In the above code objTbl is my datatable. I read the data from data table and write it to response and get the file for download.but I'm getting an error while I try to download huge files.
Insufficient memory during execution of program. I heard that response.transmit. Can solve this problem but how?
TransmitFile Writes the specified file directly to an HTTP response output stream, without buffering it in memory.
like this :
context.Response.Clear();
context.Response.ContentType = "application/octet-stream";
context.Response.AddHeader("content-disposition", "attachment; filename=ym.jpg");
context.Response.TransmitFile(context.Server.MapPath(#"~/ym.jpg"));
context.Response.End();

File downloading strange issue

I saved the document file/pdf file or txt file in the database. Now to get that File I am using the code below.
JobApplicantResume oApplicantResumne = new JobApplicantResume();
DataSet dsApplicantResume = oApplicantResumne.GetJobApplicantResumeByJobApplicantResumeId(1552);//1552 Long value
Response.ClearContent();
Response.ClearHeaders();
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/xx-xxxx";
Response.AddHeader("Content-Disposition", "attachment;filename=" + dsApplicantResume.Tables[0].Rows[0]["sFileName"].ToString());
//Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
Byte[] bytes = (Byte[])dsApplicantResume.Tables[0].Rows[0]["binFile"];
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
It is giving the exact file. No problem is there to open the file.
In some other page I used the same code:
JobApplicantResume oApplicantResumne = new JobApplicantResume();
DataSet dsApplicantResume = oApplicantResumne.GetJobApplicantResumeByJobApplicantResumeId(1552);//1552 Long value
Response.ClearContent();
Response.ClearHeaders();
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/xx-xxxx";
Response.AddHeader("Content-Disposition", "attachment;filename=" + dsApplicantResume.Tables[0].Rows[0]["sFileName"].ToString());
//Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
Byte[] bytes = (Byte[])dsApplicantResume.Tables[0].Rows[0]["binFile"];
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
It is also giving a file to download. But when I open it the data are coming in some different format.
Like:
؟½ï؟½ï؟½ï؟½ï؟½ï؟
Junk data. I could not understand why the problem is coming. If any one faced this similar kind of issue or any suggestion / help will be very much helpful to overcome this problem.
Thanks a lot for your attention.
Try to add Unicode Byte-Order-Mark full example.
//add the BOM
byte[] bBOM = new byte[] { 0xEF, 0xBB, 0xBF };
byte[] bContent = ms.ToArray();
byte[] bToWrite = new byte[bBOM.Length + bContent.Length];
//combile the BOM and the content
bBOM.CopyTo( bToWrite, 0 );
bContent.CopyTo( bToWrite, bBOM.Length );
//write to the client
HttpContext.Current.Response.Write( Encoding.UTF8.GetString( bToWrite ) );
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();

Categories