//Directory where images are stored on the server
String dist = "~/ImageStorage";
//get the file name of the posted image
string imgName = image.FileName.ToString();
String path = Server.MapPath("~/ImageStorage");//Path
//Check if directory exist
if (!System.IO.Directory.Exists(path))
{
System.IO.Directory.CreateDirectory(MapPath(path)); //Create directory if it doesn't exist
}
//sets the image path
string imgPath = path + "/" + imgName;
//get the size in bytes that
int imgSize = image.PostedFile.ContentLength;
if (image.PostedFile != null)
{
if (image.PostedFile.ContentLength > 0)//Check if image is greater than 5MB
{
//Save image to the Folder
image.SaveAs(Server.MapPath(imgPath));
}
}
I would like to create a directory of folder on the server were the application is, the folder should store all images uploaded by users. the code above is not working:
Server Error in '/' Application. 'c:/users/lameck/documents/visual studio 2012/Projects/BentleyCarOwnerAssociatioServiceClient/BentleyCarOwnerAssociatioServiceClient/ImageStorage' is a physical path, but a virtual path was expected. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Web.HttpException: 'c:/users/lameck/documents/visual studio 2012/Projects/BentleyCarOwnerAssociatioServiceClient/BentleyCarOwnerAssociatioServiceClient/ImageStorage' is a physical path, but a virtual path was expected.
Source Error:
Line 36: if (!System.IO.Directory.Exists(path)) Line 37: { Line 38: System.IO.Directory.CreateDirectory(MapPath(path)); //Create directory if it doesn't exist Line 39: } Line 40:
Source File: c:\Users\Lameck\Documents\Visual Studio 2012\Projects\BentleyCarOwnerAssociatioServiceClient\BentleyCarOwnerAssociatioServiceClient\registerCar.aspx.cs Line: 38
Any one, please help here. Your help is highly appreciated.
Sunny SharmaPosted May 25, 2013, 1:13 PM
At the very first, Server.MapPath() will return a path string only if it finds the given virtual directory. It means it will never return a Path to a non-existing virtual directory. If you know the physical path already then just go with that, you don't need to use Server.MapPath() at all. If you want to save the files to the virtual directory instead then perhaps you'll have to ensure it already exist.
Happy Coding :)
Please don't forget to accept this as answer if it helps!
Thanks.