Search code examples
c#asp.netvisual-studio-2012subdirectoryloading-image

Loading images in subfolders is not working on the server


I'm working on a project which is in two languages English and Arabic. The arabic version is in a subfolder (Ar).

Everything works fine for both versions in the visual studio local host. But when I deployed the website to the real server. I noticed that the Images in the arabic version will get the same path as the english version (so the images will not be displayed).

I upload the images in the subfolder via this code:

string fileExt = System.IO.Path.GetExtension(fileBgUpload.FileName);
string filename;
string guid = Guid.NewGuid().ToString();
try
{
    if (fileExt != "")
    {
        if (fileExt == ".jpg" || fileExt == ".jpeg" || fileExt == ".JPG" || fileExt == ".JPEG")
        {
            if (fileBgUpload.HasFile)
            {
                filename = Path.GetFileName(fileBgUpload.FileName);
                fileBgUpload.SaveAs(Server.MapPath("/img/Gallery/") +  filename + guid + ".jpg");
                imgBackground.ImageUrl = ("/img/Gallery/") + filename + guid + ".jpg";
            }
        }
    }
}

so in the Database the image url would be

/img/Gallery/Imagename.jpg

In visual studio, when I run the website everything works fine. The image Url is :

localhost:1020/Ar/img/Gallery/Imagename.jpg  

The same thing on the server (Host), gives the following URL to the image:

www.mydomain.com/img/Gallery/Imagename.jpg

This is my problem, the image will not be displayed as it gets the main folder's path.

Any ideas? can anyone tell me what i'm doing is correct ? and why in visual studio everything works fine in this case.


Solution

  • When you deploy your website, The server uses IIS, and the folder (Ar) most likely is changed to a Virtual Directory.

    In the Visual Studio, the first thing you should do is to change the Visual studio local server to IIS Express. Then, create a virtual directory for (Ar) folder, and see if you get the same results.

    To create a virtual directory please read it here

    The last thing you should modify in your code is adding "/Ar/" to the string path even before saving it in the Database.

    for example

    imgPathForDb="/Ar/"+ your string path
    

    or

    "/Ar/img/Gallery/" + filename + guid + ".jpg";
    

    Most of the developers prefer IIS rather than Visual studio local server. That's why I strongly recommend you to use IIS Express in your future projects.