【问题标题】:Handle UnauthorizedAccessException When Directory.CreateDirectory() RunDirectory.CreateDirectory() 运行时处理 UnauthorizedAccessException
【发布时间】:2016-10-21 06:43:55
【问题描述】:

我有一个方法可以帮助创建目录 ifNotExist 并保存文件的路径,... 现在我有一个小问题,Directory.CreateDirectory(savePath); 运行时出现异常。我仍然无法正确处理。我想知道我做错了什么以及如何解决它。欢迎任何人服从。谢谢

这是我的方法:

protected void ASPxUpload_FileUploadComplete(object sender, DevExpress.Web.FileUploadCompleteEventArgs e)
    {
        if (e.IsValid)
        {
            String savepath = String.Format("{0}{1}\\", MapPath(@"~\TicketUploads\"), Session["lastcallid"]);
            if (!Directory.Exists(savepath))
            {
                Directory.CreateDirectory(savepath);
            }
            String savefile = String.Format("{0}{1}", savepath, e.UploadedFile.FileName);
            e.UploadedFile.SaveAs(savefile);
            String urlPath = String.Format("{0}{1}\\{2}", @"~\TicketUploads\", Session["lastcallid"], e.UploadedFile.FileName);
            fault_detail fltdet = session.GetObjectByKey<fault_detail>(Convert.ToInt32(Session["lastcallid"]));
            fltdet.hasattachment = "Y";
            fltdet.AttachUrl = urlPath;
            fltdet.Save();
        }
    }

有关我尝试做什么的更多详细信息: 它简单地允许 Web 服务器识别日志用户的 ID。并使用该 ID,因此我们应该在 Ticketuploads 文件夹中创建一个文件夹。这就像我们试图同时创建 2 个文件夹。这就是我使用的原因:"{0}{1}\\"

【问题讨论】:

  • 建议:请使用Path.Combine而不是String.Format
  • 尝试以管理员身份运行。
  • @AmeyKamat,感谢您的回复。但我只是尝试了你所说的。我有一个错误用户:Session["lastcallid"] 它说:Caanot convert from object to String。
  • @CodeJoy,我已经以管理员身份运行了,谢谢。
  • @CodeJoy,这里是完整的异常消息:An exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.dll but was not handled in user code

标签: c#


【解决方案1】:

请试试这个

string sessionVariable = Convert.ToString(Session["lastcallid"]); 

string path = Path.Combine(MapPath(@"~\TicketUploads\"), sessionVariable);
if (!Directory.Exists(path))
{
    Directory.CreateDirectory(path);
}

还有

我已向文件夹添加管理权限。作为具有 IIS 系统的本地用户。用户添加示例:IIS_IUSRS(Username\IIS_IUSRS) 就是这样。

【讨论】:

  • UnauthorizedAccessException was handle 仍在铸造。可能需要许可,但我也试过这个:[stackoverflow.com/questions/5802000/…(Go to properties --&gt; Sharing --&gt; Advanced Sharing --&gt; Permissions) Stiil Not Working for me.
  • @MichealP。你能给出你得到例外的Session["lastcallid"] 的值吗
  • Session["lastcallid"] = 1250057。它允许网络服务器识别日志用户的ID。并使用该 ID,因此我们应该在 Ticketuploads 文件夹中创建一个文件夹。这就像我们试图同时创建 2 个文件夹。这就是我使用的原因:"{0}{1}\\"
  • @MichealP.上面的代码有效。我的代码中唯一的变化是string sessionVariable = Convert.ToString(1250057); string path = Path.Combine(@"E:\TicketUploads\", sessionVariable);
  • 你在写,这解决了。我去寻找应用程序设置的许可。我发现整个文件夹不允许用户添加任何子文件夹。此外,通过将我的路径转换为字符串,我可以清楚地看到根目录!谢谢你的一切。
猜你喜欢
  • 2021-05-07
  • 1970-01-01
  • 1970-01-01
  • 2011-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多