downloaded pdf file not opening - c#

I am saving a pdf file in the database by the following code
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
string filetype = Path.GetExtension(FileUpload1.PostedFile.FileName);
int filesize = FileUpload1.PostedFile.ContentLength;
Stream fs = FileUpload1.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
byte[] content = br.ReadBytes((Int32)fs.Length);
Objects.Insert_FilesToDatabase(filename, filetype, content,filesize);
and then, Iam trying to save the file from the database by clicking the link thru the following code.
void lnkDownload_Click(object sender, EventArgs e)
{
string filetype = Objects.GetFileType(Convert.ToInt32(txtslno.Text.Trim()));
string filename=Objects.GetFileName(Convert.ToInt32(txtslno.Text.Trim()));
int filesize = Objects.GetFileLength(Convert.ToInt32(txtslno.Text.Trim()));
byte[] bytfile = new byte[filesize+1000];
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition",attachment;filename="+filename+".pdf");
Response.BufferOutput = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(bytfile);
Response.End();
}
Thru this code, I am able to download the pdf file but I am unable to open the pdf file. The error is the file is not decoded properly. Can you help me as to where am I going wrong?

I solved this problem thru the following code..
byte[] bytfile = Objects.GetFile(Convert.ToInt32(txtslno.Text.Trim()));
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment;filename="+filename);
Response.AddHeader("Content-Length", bytfile.Length.ToString());
Response.OutputStream.Write(bytfile, 0, bytfile.Length);
Response.Flush();
Response.End();
I am just not writing the binary content to the output pdf stream in my previous code..
Thank you for your support

Related

excel cannot open the file because the file format or file extension is not valid c#

I am trying to download an excel file which for which I am giving the proper path. But after downloading it when I am trying to open I get error as
excel cannot open the file because the file format or file extension is not valid. Verify that file has been corrupted...
But If I open that file directly it gets open, I don't understand what is the issue in it. Below is my code
protected void MultipleSpanLinkIdDownLoadbtn_Click(object sender, EventArgs e)
{
try
{
string fileName = "multiSpanLinkeid.xlsx";
FileInfo file = new FileInfo(System.Configuration.ConfigurationManager.AppSettings["MultipleSpanLinkFolder"].ToString() + "/" + fileName);
if (file.Exists)
{
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
Response.AddHeader("Content-Type", "application/Excel");
Response.ContentType = "application/vnd.xls";
Response.AddHeader("Content-Length", file.Length.ToString());
Response.WriteFile(file.FullName);
Response.End();
}
else
{
Response.Write("This file does not exist.");
}
}
catch (Exception)
{
ClientScript.RegisterStartupScript(this.GetType(), "Exception", "alert('Template downloaded.');", true);
}
}
Please suggest what is wrong in this
NOTE: The issue arises while downloading it from Chrome
Please try with this content type.
Response.ContentType = "application/vnd.ms-excel";
or
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Try this:
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

Display .jpg / .png image from folder in browser instead of downloading it ASP.NET

I am trying to display .png / .jpg image in browser but the problem is instead of displaying the image in the browser it is getting downloaded. I have tried using content-disposition:inline as well but its downloading the complete aspx page. Can anyone help me with this. Below is my code
string filePath = "C:\\inetpub\\wwwroot\\Folder\\OSP\\20139000\\";
string filename = "test.jpg";
string contenttype = "image/" +
Path.GetExtension(filename.Replace(".", ""));
FileStream fs = new FileStream(filePath + filename,
FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
br.Close();
fs.Close();
////Write the file to response Stream
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = contenttype;
Response.AddHeader("content-disposition", "attachment;filename=" + filename);
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
You miss
Response.Clear();
somewhere at the beginning of the script. Without clearing the response's buffer first, it already contains the text of the *.aspx page the script is run under.
Then, don't set the content's disposition to attachment, completely delete this line.

Converting a byte[]-Array to ANSI

I am trying to convert a byte[] blob in an MSSQL database to Windows-1252 ANSI format using C# and Microsoft Lightswitch, and return the results to a file download.
This is what I thought should work...
I'm creating the string with
System.Text.Encoding v_Unicode = System.Text.Encoding.Unicode;
System.Text.Encoding v_ANSI_Windows_1252 = System.Text.Encoding.GetEncoding(1252);
string v_Content_1252 = v_ANSI_Windows_1252.GetString(System.Text.Encoding.Convert(v_Unicode, v_ANSI_Windows_1252, v_Unicode.GetBytes(v_Content)));
byte[] ansiArray = v_ANSI_Windows_1252.GetBytes(v_Content_1252);
and write it in the database. When I try to retrieve with
int v_fileId = Int32.Parse(context.Request.QueryString["p_FileId"]);
DataTableName v_fexpd = serverContext.DataWorkspace.ApplicationData.DataTableName_SingleOrDefault(v_fileId);
MemoryStream memStream = new MemoryStream(v_fexpd.Inhalt);
string v_Content= System.Text.Encoding.GetEncoding(1252).GetString(v_fexpd.Content);
context.Response.Clear();
context.Response.ContentType = "text/csv";
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + v_fexpd.Filename);
context.Response.Write( v_Content );
context.Response.End();
... but it just returns Unicode. What am I doing wrong?
This is for anyone having a similar problem. The answer is to go the way over a Stream... What I did is the following:
// Create a temporary file, delete if it already exists
string MyFile = Path.GetTempPath() + v_fexpd.Dateiname;
if (File.Exists(MyFile)) {
File.Delete(MyFile);
}
using (TextWriter tw = new StreamWriter(MyFile.ToString(), true, System.Text.Encoding.GetEncoding(1252)))
tw.WriteLine(v_Inhalt);
context.Response.Clear();
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + v_fexpd.Dateiname);
context.Response.AddHeader("Content-Type", "text/csv; charset=windows-1252");
// Write the file - which at this point is correctly-encoded -
// directly into the output.
context.Response.WriteFile(MyFile);
context.Response.End();
// Leave no traces
File.Delete(MyFile);

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

PDF returning a corrupt file

I am using the following bit of code to send a pdf file back to the user. this works fine on my pc and on all of our test pcs. however the user is complaining the document is corrupt. When I look at the pdf file sent back in notepad I can see some HTML after the binary infomation.
protected void btnGetFile_Click(object sender, EventArgs e)
{
string title = "DischargeSummary.pdf";
string contentType = "application/pdf";
byte[] documentBytes = GetDoc(DocID);
Response.Clear();
Response.ContentType = contentType;
Response.AddHeader("content-disposition", "attachment;filename=" + title);
Response.BinaryWrite(documentBytes);
}
The issue is cause by the response object appending to the end of the file bytes the Parsed HTML for the page at the end of the file. This can be prevented by calling Response.Close(), after you
have written the file to the buffer.
protected void btnGetFile_Click(object sender, EventArgs e)
{
string title = "DischargeSummary.pdf";
string contentType = "application/pdf";
byte[] documentBytes = GetDoc(DocID);
Response.Clear();
Response.ContentType = contentType;
Response.AddHeader("content-disposition", "attachment;filename=" + title);
Response.BinaryWrite(documentBytes);
Response.End();
}

Categories