download a SQL back up file in asp.net - 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();
}
}

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

Download PDF that I already Created ASP.Net

Long story short,
I want to create button that Print out PDF file to user Computer
So firstly, I create PDF file in server database / file and then I make it downloadable to user.
With this code I can create PDF file in server,
then I searched on how to make it downloadable to user..
So far no luck, most errors said "...is a physical path, but a virtual path was expected."
here's the code
private void cetak_pdf(string s_id, string CompanyCode , string zpath)
{
bool SUCCESS = true;
string sErrMsg = "";
string sFileName = "";
DiskFileDestinationOptions diskOpts = null;
try
{
sFileName = s_id;
diskOpts = new DiskFileDestinationOptions();
diskOpts.DiskFileName = Server.MapPath("~" + "\\pdf\\" + zpath + CompanyCode + "_" + sFileName + ".pdf");
//Response.Write(diskOpts.DiskFileName);Response.End();
// this is the file created E:\GIA_25\pdf\CompanyAddress00000003_003.pdf
rptDoc.ExportOptions.ExportFormatType = ExportFormatType.PortableDocFormat;
rptDoc.ExportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
rptDoc.ExportOptions.DestinationOptions = diskOpts;
rptDoc.Export();
Response.ContentType = "application/pdf";
//Response.AppendHeader("Content-Disposition", "attachment; filename=MyFile.pdf");
Response.TransmitFile(Server.MapPath("E:\\GIA_25\\pdf\\CompanyAddress00000003_003.pdf"));
Response.End();
}
catch (Exception ex)
{
SUCCESS = false;
sErrMsg = ex.Message;
throw new Exception(sErrMsg);
}
}
help please, kinda new in this language
Sorry my fault :( here is the right code for make it downloadable
Response.ContentType = "APPLICATION/OCTET-STREAM";
// String Header = "Attachment; Filename=XMLFile.xml";
String Header = "Attachment; Filename=" + "CompanyAddress" + CompanyCode + "_" + sFileName + ".pdf";
Response.AppendHeader("Content-Disposition", Header);
System.IO.FileInfo Dfile = new System.IO.FileInfo(Server.MapPath("~" + "\\pdf\\" + "CompanyAddress" + CompanyCode + "_" + sFileName + ".pdf"));
Response.WriteFile(Dfile.FullName);

why my server.mappath() is not working in another pc?

i have project in my pc..but when i am saving my uploaded files in a folder inside my project.now when i am transferring my project in another pc the server.mappath() is not working..why??
my problem upload function
protected void addproblem_Click(object sender, EventArgs e)
{
string filepath;
if (problemupload.HasFile)
try
{
if(problemupload.PostedFile.ContentType=="application/pdf")
{
// problemupload.SaveAs("F:\\0\\My project website\\sgipc\\problems\\" + problemupload.FileName);
// filepath = "F:\\0\\My project website\\sgipc\\problems\\" + problemupload.PostedFile.FileName;
problemupload.SaveAs(Server.MapPath("\\sgipc\\problems\\" + problemupload.FileName));
filepath = Server.MapPath(problemupload.PostedFile.FileName);
string con = " ";
con = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection objsqlconn = new SqlConnection(con);
objsqlconn.Open();
string userid = Convert.ToString(Session["userid"]);
SqlCommand cmd = new SqlCommand("INSERT INTO problemtable(problemname,problempath,userid,status) Values('" + probbox.Text + "','" + filepath + "','" + userid + "','" + "pending" + "')", objsqlconn);
cmd.ExecuteNonQuery();
objsqlconn.Close();
}
else
{
Response.Write("<script>alert('" + "Only pdf format is allowed..." + "')</script>");
}
}
catch (Exception ex)
{
Response.Write("<script>alert('" + ex.ToString() + "')</script>");
}
else
{
Response.Write("<script>alert('" + "you have not specified a file..." + "')</script>");
}
}
i am getting this error
"System.InvalidOperationException: Failed to map the path '/sgipc/tutorials/v6-1446-1449.pdf'."
while uploading a file from another pc..but from my pc it works fine..
I think there is problem in Server.MapPath try with this syntax FileUploadControl.SaveAs(Server.MapPath("~/sgipc/problems/" + problemupload.FileName));
~ sign will automatic configure path from server and it is better then \\ sign for map path..

Server.map path not working in asp.net

I am using this code to download a excel file which exist in my solution. I have added a folder FileUpload and added a excel file UploadCWF.xlsx. My code is workin in local host. But not working when I host this to server.I am getting error - Could not find a part of the path. My code -
string filePath = HttpContext.Current.Server.MapPath("~/FileUpload/");
string _DownloadableProductFileName = "UploadCWF.xlsx";
System.IO.FileInfo FileName = new System.IO.FileInfo(filePath + "\\" + _DownloadableProductFileName);
FileStream myFile = new FileStream(filePath + "\\" + _DownloadableProductFileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
//Reads file as binary values
BinaryReader _BinaryReader = new BinaryReader(myFile);
//Check whether file exists in specified location
if (FileName.Exists)
{
try
{
long startBytes = 0;
string lastUpdateTiemStamp = File.GetLastWriteTimeUtc(filePath).ToString("r");
string _EncodedData = HttpUtility.UrlEncode(_DownloadableProductFileName, Encoding.UTF8) + lastUpdateTiemStamp;
Response.Clear();
Response.Buffer = false;
Response.AddHeader("Accept-Ranges", "bytes");
Response.AppendHeader("ETag", "\"" + _EncodedData + "\"");
Response.AppendHeader("Last-Modified", lastUpdateTiemStamp);
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName.Name);
Response.AddHeader("Content-Length", (FileName.Length - startBytes).ToString());
Response.AddHeader("Connection", "Keep-Alive");
Response.ContentEncoding = Encoding.UTF8;
//Send data
_BinaryReader.BaseStream.Seek(startBytes, SeekOrigin.Begin);
//Dividing the data in 1024 bytes package
int maxCount = (int)Math.Ceiling((FileName.Length - startBytes + 0.0) / 1024);
//Download in block of 1024 bytes
int i;
for (i = 0; i < maxCount && Response.IsClientConnected; i++)
{
Response.BinaryWrite(_BinaryReader.ReadBytes(1024));
Response.Flush();
}
}
catch (Exception es)
{
throw es;
}
finally
{
Response.End();
_BinaryReader.Close();
myFile.Close();
}
}
else
System.Web.UI.ScriptManager.RegisterStartupScript(this, GetType(),
"FileNotFoundWarning", "alert('File is not available now!')", true);
Please some one help me.
You should first concat filepath and filename then get path using server.mappath.
You should write code like this
string filePath = HttpContext.Current.Server.MapPath("~/FileUpload/UploadCWF.xlsx");
System.IO.FileInfo FileName = new System.IO.FileInfo(filePath);

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.

Resources