我正在尝试在创建文件后下载Excel文件,但是我遇到了以下错误:
UnauthorizedAccessException:拒绝访问路径 'C:\ Users \ user_name \ Documents \ Visual Studio 2015 \ Projects \ Project_Name \ src \ Project_Name \ wwwroot'。
文件已经成功创建,问题出在下载方法上。
我已经尝试通过以下操作解决此错误:
打开VS作为管理员 将IIS_IUSR用户添加到项目文件夹中
以下是代码:
注意:我没有在IIS中部署项目。
最好的问候。
UnauthorizedAccessException:拒绝访问路径 'C:\ Users \ user_name \ Documents \ Visual Studio 2015 \ Projects \ Project_Name \ src \ Project_Name \ wwwroot'。
文件已经成功创建,问题出在下载方法上。
我已经尝试通过以下操作解决此错误:
打开VS作为管理员 将IIS_IUSR用户添加到项目文件夹中
以下是代码:
private readonly IHostingEnvironment _hostingEnvironment;
public EmployeeController(ApplicationDbContext context, IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
public void createFile()
{
string wwwrootPath = _hostingEnvironment.WebRootPath;
string fileName = @"Employees.xlsx";
FileInfo file = new FileInfo(Path.Combine(wwwrootPath, fileName));
if (file.Exists)
{
file.Delete();
file = new FileInfo(Path.Combine(wwwrootPath, fileName));
}
using (ExcelPackage package = new ExcelPackage(file))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Employee");
worksheet.Cells[1, 1].Value = "ID";
worksheet.Cells[1, 2].Value = "Name";
worksheet.Cells[1, 3].Value = "Gender";
worksheet.Cells[1, 4].Value = "Salary (in $)";
worksheet.Cells["A2"].Value = 1000;
worksheet.Cells["B2"].Value = "Jon";
worksheet.Cells["C2"].Value = "M";
worksheet.Cells["D2"].Value = 5000;
worksheet.Cells["A3"].Value = 1001;
worksheet.Cells["B3"].Value = "Graham";
worksheet.Cells["C3"].Value = "M";
worksheet.Cells["D3"].Value = 10000;
worksheet.Cells["A4"].Value = 1002;
worksheet.Cells["B4"].Value = "Jenny";
worksheet.Cells["C4"].Value = "F";
worksheet.Cells["D4"].Value = 5000;
package.Save();
downloadFile(wwwrootPath);
}
}
public FileResult downloadFile(string filePath)
{
var mimeType = "application/vnd.ms-excel";
FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
return File(fileStream, mimeType, "Employees.xlsx");
}
注意:我没有在IIS中部署项目。
最好的问候。