views:

334

answers:

2

I have an image gallery that I created by reading the contents inside a directory. Now right away I noticed a problem when there was a "+" in the filename. Like "glas + door.jpg" would break. So I thought it was an encoding problem and since it was only the "+" sign I thought that replacing the "+" with "%2b" would solve the problem. Locally the problem was fixed but when I uploaded it to my host I noticed replacing the "+" sign with "%2b" didn't work help anymore.

So this is where I started looking at the encoding possibilities of ASP.NET. I found Server.UrlEncode and Server.UrlPathEncode. This gave me some mixed results like images that worked before wouldn't work anymore.

So what's the correct way of encoding a path and why did the replace "trick" work on my PC but not in my hosting environment?

public List<fileInfo> RenderImages()
{
    List<fileInfo> RenderImages = new List<fileInfo>();
    var Images = GetImages();

    if (Images != null)
    {
        foreach (var Image in Images)
        {
            string FullPath = Path + FolderName + "/" + Image.Name.Replace("+", "%2b");
            string ImageName = Image.Name.Replace(Image.Extension, string.Empty);

            RenderImages.Add(new fileInfo { path = FullPath, name = ImageName });
        }
    }

    return RenderImages;
}    

public class fileInfo
{
    public string path { get; set; }
    public string name { get; set; }
}

The GetImages() function gets jpg, gif and png FileInfos from a certain directory. If needed, I can post that part of code also.

If it helps, here you can see how the images break. This is with Replace("+", "%2b").

Thanks in advance.

A: 

It's not a real fix to my problem but I just replaced all the "+" signs with "plus". In the captation of the images I replaced it back with "+". It's just a work around because I wasn't able to solve my problem.

Pickels
A: 

The problem is that space can be escaped as + in URL:s and there is no way for a server to tell if you really mean + or space. Even when encoded as %2b it might be a double encoded space, so it will still turn out as a space when decoded.

To fix this, you can manually replace "+" with "%252b" instead, which will correctly decode as +.

Mats Olsson