Click here to Skip to main content
15,029,369 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying to create directory in c# using this code snippet
public JsonResult Upload()
                    DirectoryInfo di =
                        Directory.CreateDirectory("~/Images_LL/Timeline/" + "userid" + Convert.ToInt32(Session["userid"]) + "");
                catch (ArgumentNullException ex)
                    //throw ex;
                catch (Exception ex)
                    throw ex;


this line throws no exception but directory is also not created. I'm running visual studio as administrator.
Please help me figure out I have tried all exceptions one by one in catch block.
Neither throws exception not makes directory.

You're passing in an app-relative path. The Directory class doesn't know anything about ASP.NET paths. You need to map the app-relative path to a physical path first:
string virtualPath = string.Format("~/Images_LL/Timeline/userid{0}", Convert.ToInt32(Session["userid"]);
string physicalPath = Server.MapPath(virtualPath);
DirectoryInfo di = Directory.CreateDirectory(physicalPath);

Also, don't use throw ex; to re-throw an exception. If you do, you'll destroy the stack-trace. Use throw; instead.

And don't catch exceptions that you're not going to handle. Catching an exception and immediately re-throwing it has no benefit. Just remove the entire catch (Exception ex) { ... } block.
Sohaib Javed 30-Nov-15 9:10am
Thanks it worked for me. Great! Can you tell me when it was not creatign directory, why it did not trow exception?
Richard Deeming 30-Nov-15 9:20am
It probably did create the directory, but relative to the "current path". For an ASP.NET application, the current path is somewhere under the "C:\Windows\Microsoft.NET\Framework{64}\{version}\Temporary ASP.NET Files\" folder.
Use MapPath to get the physical location of the path in your webspace.[^]

Directory.CreateDirectory(Server.MapPath("~/Images_LL/Timeline/") + "userid" ... 
Sohaib Javed 30-Nov-15 9:18am

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900