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

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

Related

download a SQL back up file in asp.net

I am trying to download sql back up file but getting error :
"Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack" near respone.end()
protected void btnDownload_Click(object sender, EventArgs e)
{
try
{
string backupDestination = backupPath;
string dbNAme = dbName;
string dateStamp = DateTime.Now.ToString("yy-MM-dd#HHmm");
string backupfile = backupDestination + '\\' + dbNAme + " of " + dateStamp + ".bak";
DataTable dt = blu.queryFunction("BACKUP database " + dbNAme + " to disk='" + backupDestination + "\\" + dbNAme + " of " + dateStamp + ".Bak'");
WebClient req = new WebClient();
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.ClearContent();
response.ClearHeaders();
response.Buffer = true;
response.AddHeader("content-disposition", "attachment; filename= " + dbNAme + ".bak");
byte[] data = req.DownloadData(backupfile);
response.ContentType = "application/sql";
response.BinaryWrite(data);
response.End();
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alertscipt", "swal('Error!','Database Backup Failed." + ex.ToString() + "','warning')", true);
}
}
One issue that I see is the buffer - change the response.Buffer = true; to false
response.Buffer = false;
for big files this is wrong because its put it on a buffer but you want to send it direct to the user...
also remove the catch (Exception ex) to see other problems on your code - the ScriptManager.RegisterStartupScript is not run from the moment you have change the headers. So the issue is hidden from you.
One other better and more correct way is to create a handler and download the file from there.
If the backup file is present on the server running the application, you shouldn't be using a WebClient. Something that reads the file from local disk, e.g. TransmitFile(), would then be sufficient - like this:
string backupDestination = backupPath;
string dbNAme = dbName;
string dateStamp = DateTime.Now.ToString("yy-MM-dd#HHmm");
string backupfile = backupDestination + '\\' + dbNAme + " of " + dateStamp + ".bak";
DataTable dt = blu.queryFunction("BACKUP database " + dbNAme + " to disk='" + backupDestination + "\\" + dbNAme + " of " + dateStamp + ".Bak'");
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.ClearContent();
response.ClearHeaders();
response.Buffer = true;
response.AddHeader("content-disposition", "attachment; filename= " + dbNAme + ".bak");
response.ContentType = "application/octet-stream";
response.TransmitFile(backupfile);
response.Flush();
ok so after 72 hours i have found the error. the download button was inside update panel so i was getting "Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack"
protected void btnDownload_Click(object sender, EventArgs e)
{
try
{
string dbNAme = dbName;
string backupDestination = Server.MapPath("~/BackUp");
string dateStamp = DateTime.Now.ToString("yyyy-MM-dd#HH_mm");
string fileName = dbName + " of " + dateStamp + ".Bak";
if (!Directory.Exists(backupDestination))
{
Directory.CreateDirectory(backupDestination);
}
DataTable dt = blu.queryFunction("BACKUP database " + dbNAme + " to disk='" + backupDestination + "\\" + fileName + "'");
byte[] bytes = File.ReadAllBytes(Path.Combine(backupDestination, fileName));
// Delete .bak file from server folder.
if (Directory.Exists(backupDestination))
{
Directory.Delete(backupDestination, true);
}
Response.Clear();
Response.Buffer = false;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
catch(Exception ex)
{
string exception = ex.ToString();
}
}

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

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

File Download from remote server

I am facing a strange problem.
I have a web page(Filelibrary.aspx) to download some word/pdf files, I can download the files from local machine and direct link from my local pc. but we have a server and we are usualy accessing the site by login into the server as remote desktop. If we try to download word/pdf files from remort desk top it is downloading the web page "Filelibrary.aspx" instead of the word/pdf. we are using https. I could able to download it before when it was http.
my code:
String strFile = String.Empty;
String[] filename;
strFile = Server.MapPath(ConfigurationManager.AppSettings["TemplatePath"].ToString()) + FileName;
filename = strFile.Split('\\');
Response.Clear();
Response.Buffer = true;// Read the original file from diskFileStream *
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename[filename.Length-1]);
String ext = String.Empty;
if (strFile.IndexOf(".") > 0)
ext = (strFile.Split('.'))[1];
if (ext.ToLower() == "txt")
Response.ContentType = "text/html";
if (ext.ToLower() == "xls")
Response.ContentType = "xls/html";
if (ext.ToLower() == "pdf")
Response.ContentType = "application/pdf";
////combine the path and file name
if (File.Exists(strFile))//open the file and process it
{
FileStream sourceFile = new FileStream(strFile, FileMode.Open, FileAccess.Read);
long FileSize;
FileSize = sourceFile.Length;
Response.AddHeader("Content-Length", FileSize.ToString()); //*
byte[] getContent = new byte[(int)FileSize];
sourceFile.Read(getContent, 0, (int)FileSize);
sourceFile.Close();
Response.BinaryWrite(getContent);
}
Common.UserPageAudit(Session["User"].ToString(), "Download Templates", Session["ROLE"].ToString(), strFile + " Template downloaded");
Can anyone help me to resolve this strange issue..?
Thanks you friends...
at last I found the Problem.
I was not clearing the Header.. I have changed my code as below.
String strFile = String.Empty;
String[] filename;
strFile = Server.MapPath(ConfigurationManager.AppSettings["TemplatePath"].ToString()) + FileName;
filename = strFile.Split('\\');
// Added these two line
HttpContext.Current.Response.Cache.SetNoServerCaching();
Response.ClearHeaders();
Response.Clear();
Response.Buffer = true;// Read the original file from diskFileStream *
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename[filename.Length-1]);
String ext = String.Empty;
if (strFile.IndexOf(".") > 0)
ext = (strFile.Split('.'))[1];
if (ext.ToLower() == "txt")
Response.ContentType = "text/html";
if (ext.ToLower() == "xls")
Response.ContentType = "xls/html";
if (ext.ToLower() == "pdf")
Response.ContentType = "application/pdf";
////combine the path and file name
if (File.Exists(strFile))//open the file and process it
{
FileStream sourceFile = new FileStream(strFile, FileMode.Open, FileAccess.Read);
long FileSize;
FileSize = sourceFile.Length;
Response.AddHeader("Content-Length", FileSize.ToString()); //*
byte[] getContent = new byte[(int)FileSize];
sourceFile.Read(getContent, 0, (int)FileSize);
sourceFile.Close();
Response.BinaryWrite(getContent);
}
Common.UserPageAudit(Session["User"].ToString(), "Download Templates", Session["ROLE"].ToString(), strFile + " Template downloaded");

Send ExcelPackage file to user

I want to build ExcelPackage file on server side and than send allow user to download it.
Here is my code for file creating:
private byte[] ExcelFileCreate()
{
using (var excelPackage = new ExcelPackage())
{
excelPackage.Workbook.Properties.Author = User.Identity.Name;
excelPackage.Workbook.Properties.Title = "Skybot";
excelPackage.Workbook.Properties.Company = "Dataminds";
excelPackage.Workbook.Worksheets.Add("Selected unit folder");
var excelWorksheet = excelPackage.Workbook.Worksheets[1];
excelWorksheet.Name = "Selected unit folder";
int rowIndex = 1;
int columnIndex = 1;
do
{
var cell = excelWorksheet.Cells[rowIndex, columnIndex];
var fill = cell.Style.Fill;
fill.PatternType = ExcelFillStyle.Solid;
fill.BackgroundColor.SetColor(Color.LightGray);
columnIndex++;
} while (columnIndex != 4);
excelWorksheet.Cells[1, 1].Value = "action cell";
excelWorksheet.Cells[1, 2].Value = "time cell";
excelWorksheet.Cells[1, 3].Value = "processor cell";
excelWorksheet.Cells[2, 1].Value = "action cell";
excelWorksheet.Cells[2, 2].Value = "time cell";
excelWorksheet.Cells[2, 3].Value = "processor cell";
return excelPackage.GetAsByteArray();
}
}
And send it you user:
variant 1:
private void FileTransfer(byte[] fileBytes)
{
//Clear the response
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.Cookies.Clear();
//Add the header & other information
Response.Cache.SetCacheability(HttpCacheability.Private);
Response.CacheControl = "private";
Response.Charset = System.Text.UTF8Encoding.UTF8.WebName;
Response.ContentEncoding = System.Text.UTF8Encoding.UTF8;
Response.AppendHeader("Content-Length", fileBytes.Length.ToString());
Response.AppendHeader("Pragma", "cache");
Response.AppendHeader("Expires", "60");
Response.AppendHeader("Content-Disposition",
"attachment; " +
"filename=\"ExcelReport.xlsx\"; " +
"size=" + fileBytes.Length.ToString() + "; " +
"creation-date=" + DateTime.Now.ToString("R") + "; " +
"modification-date=" + DateTime.Now.ToString("R") + "; " +
"read-date=" + DateTime.Now.ToString("R"));
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
//Write it back to the client
Response.BinaryWrite(fileBytes);
Response.End();
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("content-disposition", "attachment;filename=test.xlsx");
Response.BinaryWrite(fileBytes);
Response.End();
}
variant 2:
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("content-disposition", "attachment;filename=test.xlsx");
Response.BinaryWrite(fileBytes);
Response.End();
variant 3:
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", fileBytes));
Response.AppendHeader("Content-Length", fileBytes.Length.ToString());
Response.BinaryWrite(fileBytes);
Response.End();
And none of them works.
There is no pop-up window with suggestion to store/open file.
Event handler that should make it works:
protected void TreeViewUnit_OnContextMenuItemClick(object sender,
RadTreeViewContextMenuEventArgs eventArgs)
{
FileTransfer(ExcelFileCreate());
}
Any ideas what is wrong?
Try
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=ExcelReport.xlsx");
Response.BinaryWrite(fileBytes);
Response.End();
It works for me as shown here.

How to export an mschart chart to excel?

I have created a chart with Mschart.I want to export the created chart to excel.
I'm using following code but when I open it in excel I just see some unknown code instead of chart.
using (var chartimage = new MemoryStream())
{
ChartAmalkerd.SaveImage(chartimage, ChartImageFormat.Png);
ExportToExcel(chartimage.GetBuffer());
}
private void ExportToExcel(byte[] input)
{
string attachment = "attachment; filename=Employee.xls";
Response.ClearContent();
Response.ContentEncoding = Encoding.GetEncoding(1256);
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.ms-excel";
Response.Buffer = true;
this.EnableViewState = false;
Response.BinaryWrite(input);
Response.Flush();
Response.Close();
Response.End();
}
I have found the same issue and after making several attempts, I was able to find out the correct way. This worked for me and the code is as follows.
string tmpChartName = "test2.jpg";
string imgPath = HttpContext.Current.Request.PhysicalApplicationPath + tmpChartName;
Chart1.SaveImage(imgPath);
string imgPath2 = Request.Url.GetLeftPart(UriPartial.Authority) + VirtualPathUtility.ToAbsolute("~/" + tmpChartName);
Response.Clear();
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment; filename=test.xls;");
StringWriter stringWrite = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
string headerTable = #"<Table><tr><td><img src='" + imgPath2 + #"' \></td></tr></Table>";
Response.Write(headerTable);
Response.Write(stringWrite.ToString());
Response.End();
Hope this helps.
I also came across such scenario in one of my project.
Here is the solution.
http://haseet.blogspot.in/2013/02/develop-chart-in-aspnet-with-export-to-excel-pdf-msoffice-openoffice.html
Add this code for your globalization, this works for me.
Dim info As System.Globalization.CultureInfo = New System.Globalization.CultureInfo("en-US")
Thread.CurrentThread.CurrentCulture = info
Thread.CurrentThread.CurrentUICulture = info
context.Response.ContentEncoding = System.Text.Encoding.UTF8
context.Response.HeaderEncoding = System.Text.Encoding.UTF8

Resources