An interesting problem occurred yesterday when I was trying to upload a file to the server. I was getting:
Access to the path '' is denied
The problem wasn't actually caused by the file upload but by my attempt to create a directory to put that file there. After reading a bunch of answers on StackOverflow, most of which related to IIS Pool modifications... Surely, I can't be that complicated. Well it wasn't:
Spot the difference?
This doesn't work:
1 2 3 4 5 6 7 8 |
string filename = file.FileName; string subPath = "~/Images/" + Object1.Object1Id; bool exists = System.IO.Directory.Exists(subPath); if (!exists) { System.IO.Directory.CreateDirectory(subPath); } file.SaveAs(HttpContext.Server.MapPath("~/Images/" + Object1.Object1Id + "/") + filename); |
This does work:
1 2 3 4 5 6 7 8 |
string filename = file.FileName; string subPath = HttpContext.Server.MapPath("~/Images/" + Object1.Object1Id); bool exists = System.IO.Directory.Exists(subPath); if (!exists) { System.IO.Directory.CreateDirectory(subPath); } file.SaveAs(HttpContext.Server.MapPath("~/Images/" + Object1.Object1Id + "/") + filename); |
It seems HttpContext.Server.MapPath("~/Images/" + Object1.Object1Id);
makes all the difference.