2013-05-25 21 views
0
//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#web應用程序中的圖像

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.

源錯誤:

36行:如果 第37行(System.IO.Directory.Exists(路徑)!):{ 第38行:System.IO .Directory.CreateDirectory(MapPath的(路徑)); //創建目錄,如果不存在39 行吧:} 第40行:

源文件:C:\用戶\ Lameck \文檔\的Visual Studio 2012 \項目\ BentleyCarOwnerAssociatioServiceClient \ BentleyCarOwnerAssociatioServiceClient \ registerCar.aspx.cs行:38

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

     } 

    } 
相關問題