使用EPPLUS保存包时出现InnerException-未经授权的访问
本文关键字:授权 访问 InnerException- EPPLUS 保存 包时出 使用 | 更新日期: 2023-09-27 18:24:38
我正试图在MVC应用程序的控制器中使用EPPLUS创建一个Excel文件。
文件似乎创建得很好,但当我试图保存时会阻塞:
[HttpPost]
public FileResult getBill(int billMonth, int billYear)
{
FileInfo newFile = new FileInfo("C:''cool.xlsx");
if (newFile.Exists)
{
newFile.Delete(); // ensures we create a new workbook
newFile = new FileInfo("cool.xlsx");
}
using (ExcelPackage package = new ExcelPackage(newFile))
{
// add a new worksheet to the empty workbook
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Inventory");
//Add the headers
worksheet.Cells[1, 1].Value = "ID";
...
// save our new workbook and we are done!
package.Save();
}
我得到的错误:Error saving file C:'cool.xlsx
System.InvalidOperationException was unhandled by user code
HResult=-2146233079
Message=Error saving file C:'cool.xlsx
Source=EPPlus
StackTrace:
at OfficeOpenXml.ExcelPackage.Save()
at ...BillingController.getBill(Int32 billMonth, Int32 billYear) in ...'Controllers'BillingController.cs:line 118
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49()
InnerException: System.UnauthorizedAccessException
HResult=-2147024891
Message=Access to the path 'C:'cool.xlsx' is denied.
Source=mscorlib
StackTrace:
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode)
at OfficeOpenXml.ExcelPackage.Save()
InnerException:
最终,我甚至不想保存它,我只想将它作为FileResult返回给用户,但我认为这是设置它的必要步骤。
System.UnauthorizedAccessException
清楚地表明这是一个权限问题。您正在保存到一个没有写入权限的目录。
尝试保存到某个子文件夹,而不是直接保存到C:驱动器。如果应用程序的IIS不足,请将文件夹的权限授予应用程序池。