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 FileInfo
s 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.