2

I have an application that uploads images, I am trying to get the path to store on the server and not on my C:drive. Below is the code in the controller:

 if (ModelState.IsValid)
        {

        if (file != null)
        {
            string ImageName = System.IO.Path.GetFileName(file.FileName);
            string physicalPath = Server.MapPath("~/Images/");

            try
            {
                if (!Directory.Exists(physicalPath))
                    Directory.CreateDirectory(physicalPath);

                string physicalFullPath = Path.Combine(physicalPath, ImageName);

                file.SaveAs(physicalFullPath);

                customer.CustomerLogo = ImageName;
                customer.CustomerLogoPath = physicalFullPath;
                db.Customers.Add(customer);
                db.SaveChanges();
            }
            catch(Exception e)
            {
                return View("Error",e.Message );
            }
        }
        return RedirectToAction("Index");

    }
    return View(customer);
}

It's currently being stored like this(See above Image) I need the path to be "admin.loyaltyworx.co.za\Images\jeep.jpg" How can I achieve this?

  • A possible duplicate question. Please check the following [question](https://stackoverflow.com/questions/17838914/c-sharp-save-files-to-folder-on-server-instead-of-local) : – Nirzar Aug 31 '17 at 07:45
  • You have accepted an answer which is completely wrong. You need to use `Server.MapPath("~/Images/");` otherwise you will never be able to access the image when you try and read it (and your only seeing that path because your creating the images on your local machine, which of course you will not be once you publish the app). –  Sep 02 '17 at 08:28
  • @StephenMuecke,the answer I accepted I tried out of course and it works even after I published. –  Sep 02 '17 at 08:30
  • Its hard-coding the path. DO NOT do that! –  Sep 02 '17 at 08:31
  • Ah I see, when I leave it as Server.MapPath("~/Images/") it didn't get saved onto the server and is unreadable once published. Do you have a suggestion on a better solution ? –  Sep 02 '17 at 08:33
  • string physicalPath = "\\admin.loyaltyworx.co.za\\Images"; this is my code currently –  Sep 02 '17 at 08:33
  • You do not need that at all. You could just save the path into the data base as `customer.CustomerLogoPath = Path.Combine("~/Images", ImageName);` and then when you want to access it (e.g. for use in an `` tag in a view), then you can use `Server.MapPath(model.CustomerLogoPath)` so it always points to the correct location no mater where you publish your app. `Server.MapPath()` should always be used to map the relative or virtual path to the corresponding physical directory on the server –  Sep 02 '17 at 08:40

1 Answers1

1

Use

string physicalPath = "c:\\admin.loyaltyworx.co.za\\Images";

Instead of

string physicalPath = Server.MapPath("~/Images/");
Ashkan Mobayen Khiabani
  • 33,575
  • 33
  • 102
  • 171