Micheal P. Micheal P. - 1 year ago 101
C# Question

Handle UnauthorizedAccessException When Directory.CreateDirectory() Run

I have a method that is helps to Create a Directory ifNotExist and Save the path of the File ,...
Now I have a little problem, There is an Exception casted when

Runs. and I can't still get it right. I would like to know what I am doing wrong and how to fix it. Anyone Subjections is welcome. Thanks

Here is My Method:

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))
String savefile = String.Format("{0}{1}", savepath, e.UploadedFile.FileName);
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;

For more details of What I trying to do:
It simple allows the web server to identify the ID of the log user. and With that ID, We should therefore create a folder in Ticketuploads Folder. Which is like we are trying to create 2 folders at the same time. That is why I use:

Answer Source

please try this

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

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


I have Add Administration Permission to the Folder. As a Local user with IIS System. user Add Example: IIS_IUSRS(Username\IIS_IUSRS) That's it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download