【发布时间】:2011-02-08 23:10:42
【问题描述】:
我有一个带有多个FileUpload 控件和一个上传按钮的aspx 页面。在点击处理程序中,我保存这样的文件:
string path = "...";
for (int i = 0; i < Request.Files.Count - 1; i++)
{
HttpPostedFile file = Request.Files[i];
string fileName = Path.GetFileName(file.FileName);
string saveAsPath = Path.Combine(path, fileName);
file.SaveAs(saveAsPath);
}
当file.SaveAs() 被调用时,它会抛出:
System.Web.HttpUnhandledException: 类型异常 'System.Web.HttpUnhandledException' 被抛出。 ---> System.UnauthorizedAccessException: 访问路径 “……” 被拒绝。在 System.IO.__Error.WinIOError(Int32 错误代码,字符串可能全路径)在 System.IO.FileStream.Init(字符串路径, FileMode 模式,FileAccess 访问, Int32 权限,布尔用户权限, FileShare 共享,Int32 bufferSize, 文件选项选项, SECURITY_ATTRIBUTES secAttrs,字符串 msgPath,布尔 bFromProxy)在 System.IO.FileStream..ctor(字符串 路径、FileMode 模式、FileAccess 访问、文件共享共享、Int32 bufferSize,FileOptions 选项, 字符串 msgPath,布尔值 bFromProxy)
在 System.IO.FileStream..ctor(字符串 路径,文件模式模式)在 System.Web.HttpPostedFile.SaveAs(字符串 文件名)在 Belden.Web.Intranet.Iso.Complaints.AttachmentUploader.btnUpload_Click(对象 发件人,EventArgs e) 在 System.Web.UI.WebControls.Button.OnClick(EventArgs 吃 System.Web.UI.WebControls.Button.RaisePostBackEvent(字符串 事件参数)在 System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler 源控件,字符串 eventArgument)
在 System.Web.UI.Page.ProcessRequestMain(布尔值 includeStagesBeforeAsyncPoint,布尔值 includeStagesAfterAsyncPoint) --- 内部异常堆栈跟踪结束 --- 在 System.Web.UI.Page.HandleError(异常 吃 System.Web.UI.Page.ProcessRequestMain(布尔值 includeStagesBeforeAsyncPoint,布尔值 includeStagesAfterAsyncPoint) 在 System.Web.UI.Page.ProcessRequest(布尔 includeStagesBeforeAsyncPoint,布尔值 includeStagesAfterAsyncPoint) 在 System.Web.UI.Page.ProcessRequest()
在 System.Web.UI.Page.ProcessRequest(HttpContext 上下文)在 ASP.departments_iso_complaints_uploadfiles_aspx.ProcessRequest(HttpContext 上下文)在 System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() 在 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean & completedSynchronously)
现在是有趣的部分。文件保存正确!那么为什么会抛出这个异常呢?
更新
我通过检查非零 ContentLength 来修复它:
string path = "...";
for (int i = 0; i < Request.Files.Count - 1; i++)
{
HttpPostedFile file = Request.Files[i];
if (file.ContentLength == 0)
{
continue;
}
string fileName = Path.GetFileName(file.FileName);
string saveAsPath = Path.Combine(path, fileName);
file.SaveAs(saveAsPath);
}
【问题讨论】:
-
尝试从现在保存文件的位置删除/移动文件并再次上传。这种情况下,错误还会出现吗?
-
我刚刚再次单步执行代码...当 FileUpload 控件之一没有路径时发生错误。它仍然会创建一个 HttpPostedFile 实例,但 ContentLength 为 0 且 FileName 为空。哇!