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);
}
}
3
Answers
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"
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:
One issue that I see is the buffer – change the
response.Buffer = true;
to falsefor 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 – theScriptManager.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.