我想在从浏览器返回一些数据之前删除文件夹及其内容。
我正在使用ASP .NET MVC 5和javascript以及一些DevExpress组件。
该方法应返回HttpResponseMessage
,即excel文件。该文件是在临时文件夹中创建的,之后我想将其删除。
我总是遇到“UnauthorizedAccessException”异常。
知道逻辑流应如何返回文件并将其删除?
我在考虑完成ExportExcelChart
之后调用一个新方法,但也许有更好的方法来实现预期的结果。
如何
JS(浏览器)
function SaveChart(s, e) {
//debugger;
if (e.item.name === 'mnuSaveToDisk') {
averageChart.printOptions.landscape = true;
averageChart.printOptions.SetSizeMode('Stretch');
averageChart.SaveToDisk('pdf', "average curves");
} else if (e.item.name == 'mnExportChart') {
ChartLoadingPanel.Show();
@*$.get('@Url.Action("ExportExcelChart", "Mindboard")', {}, null);*@
window.location = '@Url.Action("ExportExcelChart", "Mindboard")';
ChartLoadingPanel.Hide();
}
}
控制器
public HttpResponseMessage ExportExcelChart()
{
try
{
// create excel file
String tmpRandomFolderName = DataService.RandomString(20);
string tmpFolderPath = Path.Combine(Server.MapPath("~/App_Data"), "TEMP", tmpRandomFolderName);
string tmpOriginFile = Server.MapPath("~/App_Data") + "/ExportChartAverage.xlsx";
string tmpNewFile = tmpFolderPath + "/ExportChartAverage.xlsx";
if (!Directory.Exists(tmpFolderPath))
Directory.CreateDirectory(tmpFolderPath);
System.IO.File.Copy(tmpOriginFile, tmpNewFile);
// open excel file
FileInfo tmpExcelFile = new FileInfo(tmpNewFile);
ExcelPackage pck = new ExcelPackage(tmpExcelFile);
var ws = pck.Workbook.Worksheets[1];
// do stuff...
pck.SaveAs(Response.OutputStream);
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=ExportChartAverage.xlsx");
if (Directory.Exists(tmpFolderPath))
{
if (System.IO.File.Exists(tmpNewFile))
System.IO.File.Delete(tmpNewFile);
Directory.Delete(tmpFolderPath, true);
}
var response = new HttpResponseMessage(HttpStatusCode.OK);
return response;
}
catch (IOException ex)
{
var response = new HttpResponseMessage(HttpStatusCode.NotFound);
response.Content = new StringContent(ex.Message);
return response;
//throw ex;
}
catch (UnauthorizedAccessException ex)
{
var response = new HttpResponseMessage(HttpStatusCode.NotFound);
response.Content = new StringContent(ex.Message);
return response;
//throw ex;
}
catch (Exception)
{
throw;
}
}