gpt4 book ai didi

c# - 使用 ASP.NET Core 下载文件

转载 作者:太空狗 更新时间:2023-10-29 21:37:48 25 4
gpt4 key购买 nike

我在创建文件后尝试下载 excel 文件,但出现以下错误:

UnauthorizedAccessException: Access to the path 'C:\Users\user_name\Documents\Visual Studio 2015\Projects\Project_Name\src\Project_Name\wwwroot' is denied.

文件创建成功,问题出在下载方法上。

我已经尝试通过以下操作解决此错误:

  • 以管理员身份打开 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 中部署项目。

最好的问候

最佳答案

在 ASP.NET Core 中,您应该使用 PhysicalFileProvider 类来访问实际系统的文件。如果你查看 File providers文档中的部分:

The PhysicalFileProvider provides access to the physical file system. It wraps the System.IO.File type (for the physical provider), scoping all paths to a directory and its children. This scoping limits access to a certain directory and its children, preventing access to the file system outside of this boundary.

以下应该适合您:

string wwwrootPath = _hostingEnvironment.WebRootPath;
string fileName = @"Employees.xlsx";

IFileProvider provider = new PhysicalFileProvider(wwwrootPath);
IFileInfo fileInfo = provider.GetFileInfo(fileName);
var readStream = fileInfo.CreateReadStream();

//PhysicalFileProvider.GetFileInfo 返回提供 IFileInfo.CreateReadStream 方法实现的 PhysicalFileInfo 实例。

关于c# - 使用 ASP.NET Core 下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44432294/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com