Mark Tabor

Mark Tabor

  • 569
  • 1.9k
  • 431.2k

server.MapPath in c# mvc

May 18 2021 4:24 AM
Hi I have an application which works fine when i run it using visual studio, I am saving employee name , photo and email it works fine and save the file to the directory in my project -->employee Photo Folder , Now when I deploy this application to IIS ( i have checked to put the published folder on DESKTOP as well as in wwwroot
folder as well .
 
but when saving the record from the deployed application it did not get saved and i am unable to debug as it is deployed as per my understanding server.MAPPATH does not work on iss
 
below is the code which works fine with visual studio
  1. if (upload != null && upload.ContentLength > 0 && upload.ContentLength < 41943040)  
  2. {  
  3. var avatar = new File  
  4. {  
  5. FileName = System.IO.Path.GetFileName(upload.FileName),  
  6. FileType = FileType.Avatar,  
  7. ContentType = upload.ContentType  
  8. };  
  9. File fl = new File();  
  10. fl.FileName = System.IO.Path.GetFileName(upload.FileName);  
  11. string pic = System.IO.Path.GetFileName(upload.FileName);  
  12. string path = System.IO.Path.Combine(  
  13. Server.MapPath("~/StudentPhotos/"), pic);  
  14. var allowedExtensions = new[] {  
  15. ".jpg"".png"".jpeg"".gif"".svg"  
  16. };  
  17. // check file is empty or not  
  18. if (upload != null)  
  19. {  
  20. // check the bytes of file is greater than 0  
  21. if (upload.ContentLength > 0)  
  22. {  
  23. // get the uploaded file extension  
  24. string ext = System.IO.Path.GetExtension(upload.FileName).ToLower();  
  25. // check the file extension is valid or not  
  26. if (allowedExtensions.Contains(ext))  
  27. {  
  28. // replace name for uniquness and add ext  
  29. //this below line generate new name of file  
  30. string name = upload.FileName.ToLower();  
  31. // this line is for make path to save in databaseget un  
  32. string rootpath = "/StudentPhotos/"//in ur case it makes like /ProfileImages/Logo.jpg  
  33. //this below code is save file in folder  
  34. // this line makes ABSOLUTE path like E://someFolder/someOtherFolders/filename.ext  
  35. // because file is saved into physical address  
  36. string s = System.IO.Path.Combine(System.Web.HttpContext.Current.Server.MapPath(rootpath), name);  
  37. // finally this line copy paste the image to s path  
  38. upload.SaveAs(s);  
  39. student.Student_photo = "~/StudentPhotos/" + name;  
  40. }  
  41. }  
  42. }  
  43. }  
  44. else  
  45. {  
  46. ModelState.AddModelError("", errorMessage: "you cannot add file having size more than 40 MB ");  
  47. return View();  
  48. }  

Answers (3)