Unable to cast object of type 'system.string' to type 'system.Byte[]' when trying to download a file from database - asp.net

I am trying to download a file from database but its giving me an error called Unable to cast object of type 'System.String' to type 'System.Byte[]' on the line : Response.AddHeader("Content-Length", bytes.ToString());
Please tell me how can I cast string to byte in my case, thank you in advance.
I have a column named SaleFileName from which I want to download a file.
Aspx code:
<asp:TemplateField HeaderText="RecieptName" SortExpression="RecieptName">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="Download" CommandArgument='<%# Bind("SaleName") %>' Text='<%# Bind("SaleName") %>' ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
Code Behind File:
protected void gridContributions_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Download")
{
// make sure fileName contains only file name like 'test.pdf'
string FileName = Convert.ToString(e.CommandArgument);
// make sure filePath contains file path like 'Uploads/Scheme/test.pdf'
string FilePath = e.CommandArgument.ToString();
string connectionString = WebConfigurationManager.ConnectionStrings["ConnectionString2"].ConnectionString;
// SqlConnection con = new SqlConnection(connectionString);
// byte[] bytes;
//string ContentType;
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "selectSaleFileName from Contributions where SaleFileName = #SaleFileName";
cmd.Parameters.AddWithValue("#SaleFileName", FileName);
//d.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
con.Open();
using ( SqlDataReader sdr = cmd.ExecuteReader())
{
sdr.Read();
bytes = (byte[])sdr["SaleFileName"];
//byte data = System.Text.Encoding.Unicode.GetBytes(SaleFileName.ToString);
}
con.Close();
}
}
Response.Clear();
Response.Buffer = true;
// Read the original file from disk
FileStream myFileStream = new FileStream( FilePath ,FileMode.Open);
long FileSize = myFileStream.Length;
byte[] Buffer = new byte[Convert.ToInt32(FileSize)];
myFileStream.Read(Buffer, 0, Convert.ToInt32(FileSize));
myFileStream.Close();
// // Tell the browse stuff about the file
Response.AddHeader("Content-Length", bytes.ToString());
// Response.AddHeader("Content-Length", FileNam
//Response.AddHeader("Content-Disposition", "inline; filename=" & fileName.Replace(" ", "_"));
Response.AddHeader("Content-Disposition", "attachment; FileName=" + FileName + ";");
Response.TransmitFile(FileName);
Response.ContentType = "application/octet-stream";
// Send the data to the browser
Response.BinaryWrite(Buffer);
Response.End();
}
}

You can't cast byte[] to string (unless its textual data and you should encode the data using any encoding like unicode, ASCII)
anyway, the problem in the Content-Length on http header, it should be the length of the file
so replace this line:
Response.AddHeader("Content-Length", bytes.ToString());
with this:
Response.AddHeader("Content-Length", FileSize.ToString());
if the file is stored databaase you need to get it as byte array, the following code will help you:
private byte[] ReadFileFromDatabase(string FileName) {
string connectionString = WebConfigurationManager.ConnectionStrings["ConnectionString2"].ConnectionString;
byte[] bytes = null;
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "selectSaleFileName from Contributions where SaleFileName = #SaleFileName";
cmd.Parameters.AddWithValue("#SaleFileName", FileName);
cmd.Connection = con;
con.Open();
using ( SqlDataReader sdr = cmd.ExecuteReader())
{
if (sdr.Read() )
bytes = (byte[])sdr["SaleFileName"];
}
con.Close();
}
}
return bytes;
}
protected void gridContributions_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Download")
{
string FileName = Convert.ToString(e.CommandArgument);
byte[] bytes = ReadFileFromDatabase(FileName);
Response.Clear()
Response.ContentType = "application/octet-stream"
Response.AddHeader("Content-Disposition", "attachment; FileName=" + FileName + ";");
Response.BinaryWrite(bytes)
Response.End()
}
}
if your file is stored outside database:
public static void DownloadFile(string path, string contentType)
{
FileInfo file = new FileInfo(path);
if (file.Exists)
{
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AddHeader("Content-Type", contentType);
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.Flush();
Response.TransmitFile(file.FullName);
Response.End();
}
}
call it as:
string fullPath = Server.MapPath(relativePath);
DownloadFile(fullPath , "application/octet-stream");

Related

How to Remove default underscore in asp.net while downloading the file

protected void DownloadFile(object sender, EventArgs e)
{
string param = Request.QueryString["id"];
//int id = int.Parse((sender as LinkButton).CommandArgument);
//byte[] bytes;
string fileName;
SqlCommand cd = DbCon._dbConnection.CreateCommand();
cd.CommandType = CommandType.Text;
cd.CommandText = "select id from student_registration where id = '" + param + "'";
cd.ExecuteNonQuery();
SqlCommand cmd = DbCon._dbConnection.CreateCommand();
cmd.CommandText = "select books_pdf from books where id = '" + param + "'";
// cmd.Parameters.AddWithValue("#Id", param);
String s1 = cmd.ExecuteScalar().ToString();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
sdr.Read();
//bytes = (byte[])sdr["Data"];
//contentType = sdr["ContentType"].ToString();
fileName = sdr["books_pdf"].ToString();
}
Response.Clear();
Response.Buffer = true;
Response.Charset = "/";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
//Response.ContentType = contentType;
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName );
//Response.AppendHeader("Content-Disposition", "attachment; filename=" +fileName);
// Response.TransmitFile(Server.MapPath("~/Files/"+ fileName));
// Response.WriteFile(file.FullName);
Response.Flush();
Response.End();
}
This is the code where I have written to download the file. but the result what am getting correct file but '/' is replaced with 'underscore;
My question is how to remove that underscore and add '/' in place of underscore I have attached the image please check that and please help me in finding the solutionenter image description here
enter image description here
image shows the path stored in database and error what I am facing to download
fileName = "../librarian/" + sdr["books_pdf"].ToString();
}
WebClient req = new WebClient();
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.ClearContent();
response.ClearHeaders();
response.Buffer = true;
response.AddHeader("Content-Disposition", "attachment;filename=\"" + Server.MapPath(fileName) + "\"");
byte[] data = req.DownloadData(Server.MapPath(fileName));
response.BinaryWrite(data);
response.End();
Proper Selection of File was not given later i corrected proper file location than i got proper output

iTextSharp 7 - Save Dialog

Can anyone tell me how can I create a pdf file using iTextSharp 7 and popup a save dialog instead of saving it to a specific disk location?
My test code is the following:
protected void btnPrint_OnClick(object sender, EventArgs e)
{
Document doc = new Document(PageSize.A4, 25f, 20f, 20f, 10f);
var output = new FileStream(Server.MapPath("MyFirstPDF.pdf"), FileMode.Create);
var writer = PdfWriter.GetInstance(doc, output);
doc.Open();
doc.Add(new Paragraph("test!"));
doc.Close();
}
The workaround I found is the following:
After creating the document:
string path = "C:\\...";
string fileName = "PdfFile.pdf";
FileInfo fileInfo = new FileInfo(path);
Byte[] FileBuffer = File.ReadAllBytes(fileInfo.FullName);
if (FileBuffer != null)
{
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.AddHeader("content-length", FileBuffer.Length.ToString());
Response.BinaryWrite(FileBuffer);
Response.Flush();
//DELETE FILE AFTER DOWNLOAD
fileInfo.Delete();
Response.End();
}

Retrieve PDF file stored in SQL Server database and then display on page

I'm working on asp.net application where it display the retrieved pdf file from database on the page. I'm facing problem where the pdf file is not displaying in the page
With this I'm attaching my code that I have tried:
con.Open();
SqlCommand cmd = new SqlCommand("select Pdf from SavePdf where IC='" + id +
"'", con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
byte[] fileData = (byte[])dr.GetValue(0);
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/pdf";
Response.BinaryWrite(fileData);
Response.Flush();
Response.End();
}
dr.Close();
}
Use this code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
int id = int.Parse(Request.QueryString["id"]);
Display(id);
}
}
private void Display(int id)
{
DataSet ds = GetData("select * from tblFiles where Id=#Id", id);
Byte[] bytes = (Byte[])ds.Tables[0].Rows[0]["Data"];
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/pdf";
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
private DataSet GetData(string query, int id)
{
string conString = ConfigurationManager.ConnectionStrings["constr_files"].ConnectionString;
SqlCommand cmd = new SqlCommand(query);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
cmd.Parameters.Add("#Id", id);
sda.SelectCommand = cmd;
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
return ds;
}
}
}
}
I tried your code and it works perfect for me.
protected void ShowPdfButton_Click(object sender, EventArgs e)
{
byte[] fileData = GetPdfBytes();
Response.Buffer = true;
Response.Charset = "";
Response.Clear();
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/pdf";
Response.BinaryWrite(fileData);
Response.Flush();
Response.End();
}
private byte[] GetPdfBytes()
{
string pdfFileFullName = #"C:\Reports\Test.pdf";
//TODO: you can fetch the bytes from database as well and return. i have used pdf file.
return System.IO.File.ReadAllBytes(pdfFileFullName);
}

Unable to get the Content of the text file saved in the Database(My-Sql)

In my MySql i am having my data field as longblob i would like to get the content in that file so i have written my code as follows
This is what i am doing before inserting
string filePath = Server.MapPath("AchTemplates/genACH.txt");
string filename = Path.GetFileName(filePath);
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
br.Close();
fs.Close();
string strQuery = "insert into tblFiles(FName,FData) values (#_FName, #_FData)";
MySqlCommand cmd = new MySqlCommand(strQuery);
cmd.Parameters.Add("#_FName", MySqlDbType.VarChar).Value = filename;
cmd.Parameters.Add("#_FData", MySqlDbType.LongBlob).Value = bytes;
InsertUpdateData(cmd);
//Get Data
private void download(DataTable dt)
{
Byte[] bytes = (Byte[])dt.Rows[0]["FData"];
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = dt.Rows[0]["ContentType"].ToString();
Response.AddHeader("content-disposition", "attachment;filename="
+ dt.Rows[0]["Name"].ToString());
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
But i am getting the content as system.string[] why it is happening can any one tell
if dt.Rows[0]["FData"] is coming as a string (it is just plain text), use
byte[] bytes = Encoding.UTF8.GetBytes(dt.Rows[0]["FData"]);
If the data is not plain text and binary stored as string (and not base64 encoded), you are in trouble my friend.
UPDATE
According to MySql documentation, it seems you should be using LONGBLOB and not LONGTEXT.

How I can export a datatable to MS word 2007, excel 2007,csv from asp.net?

I am using the below code to Export DataTable to MS Word,Excel,CSV format & it's working fine. But problem is that this code export to MS Word 2003,Excel 2003 version. I need to Export my DataTable to Word 2007,Excel 2007,CSV because I am supposed to handle more than 100,000 records at a time and as we know Excel 2003 supports for only 65,000 records.
Please help me out if you know that how to export DataTable or DataSet to MS Word 2007,Excel 2007.
public static void Convertword(DataTable dt, HttpResponse Response,string filename)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=" + filename + ".doc");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.word";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
System.Web.UI.WebControls.GridView dg = new System.Web.UI.WebControls.GridView();
dg.DataSource = dt;
dg.DataBind();
dg.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
//HttpContext.Current.ApplicationInstance.CompleteRequest();
}
public static void Convertexcel(DataTable dt, HttpResponse Response, string filename)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=" + filename + ".xls");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
System.Web.UI.WebControls.DataGrid dg = new System.Web.UI.WebControls.DataGrid();
dg.DataSource = dt;
dg.DataBind();
dg.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
//HttpContext.Current.ApplicationInstance.CompleteRequest();
}
public static void ConvertCSV(DataTable dataTable, HttpResponse Response, string filename)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=" + filename + ".csv");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "Application/x-msexcel";
StringBuilder sb = new StringBuilder();
if (dataTable.Columns.Count != 0)
{
foreach (DataColumn column in dataTable.Columns)
{
sb.Append(column.ColumnName + ',');
}
sb.Append("\r\n");
foreach (DataRow row in dataTable.Rows)
{
foreach (DataColumn column in dataTable.Columns)
{
if(row[column].ToString().Contains(',')==true)
{
row[column] = row[column].ToString().Replace(",", "");
}
sb.Append(row[column].ToString() + ',');
}
sb.Append("\r\n");
}
}
Response.Write(sb.ToString());
Response.End();
//HttpContext.Current.ApplicationInstance.CompleteRequest();
}
Use application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

Resources