我想创建一个文件夹来存储C#Web应用程序中的图像

时间:2013-05-25 16:03:14

标签: c# asp.net

//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));

    }

}

我想在应用程序服务器上创建一个文件夹目录,该文件夹应该存储用户上传的所有图像。上面的代码不起作用:

  '/'应用程序中的服务器错误。   'c:/ users / lameck / documents / visual studio 2012 / Projects / BentleyCarOwnerAssociatioServiceClient / BentleyCarOwnerAssociatioServiceClient / ImageStorage'是物理路径,但预计会有虚拟路径。   描述:执行当前Web请求期间发生未处理的异常。请查看堆栈跟踪,以获取有关错误及其在代码中的起源位置的更多信息。

     

异常详细信息:System.Web.HttpException:'c:/ users / lameck / documents / visual studio 2012 / Projects / BentleyCarOwnerAssociatioServiceClient / BentleyCarOwnerAssociatioServiceClient / ImageStorage'是物理路径,但需要虚拟路径。

来源错误:

第36行:if(!System.IO.Directory.Exists(path)) 第37行:{ 第38行:System.IO.Directory.CreateDirectory(MapPath(path)); //创建目录(如果它不存在) 第39行:} 第40行:

源文件:c:\ Users \ Lameck \ Documents \ Visual Studio 2012 \ Projects \ BentleyCarOwnerAssociatioServiceClient \ BentleyCarOwnerAssociatioServiceClient \ registerCar.aspx.cs Line:38

1 个答案:

答案 0 :(得分:1)

您不应该对同一路径使用MapPath()两次。

旧代码:

System.IO.Directory.CreateDirectory(MapPath(path)); //Create directory if it doesn't exist

更正代码:

System.IO.Directory.CreateDirectory(path); //Create directory if it doesn't exist

编辑:也更正了这个:

string imgPath = path + "/" + imgName;

对此:

string imgPath = Path.Combine(path, imgName);

整个更正后的代码:

  //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(path); //Create directory if it doesn't exist
    }

    //sets the image path
    string imgPath = Path.Combine(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(imgPath);

        }

    }