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);
}
}
CodePudding user response:
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();
CodePudding user response:
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.