File.Exists and Accentuation

4

I have a system developed in Webforms (eca!) that checks the existence of an image and then displays it.

Everything is working correctly, however, when the image path has accents, the File.Exists method seems to be returning false .

What can I do to get around this?

Example:

 string img1 = Server.MapPath("\Fotos\Imagem.jpg");
 string img2 = Server.MapPath("\Fotos\Imagem-com-acentuação.jpg");

Console.WriteLine(File.Exists(img1)); // true
Console.WriteLine(File.Exists(img2)); // false

Update: I wrote and tested the existence of a manually accented file and it worked. I begin to suspect that the problem is in the assembly of the file path, which was done as follows:

string imgUrl = "~\Fotos\Fotos_" + Codigo + "\" + e.Row.Cells[20].Text;
    
asked by anonymous 23.05.2018 / 14:20

2 answers

2

It is possible that the string with the file name being encoded in HTML, you can reverse this using HtmlEncode and HtmlDecode :

string arquivo = "Imagem-com-acentuação.jpg";

string codificada = Server.HtmlEncode(arquivo); //Imagem-com-acentuação.jpg

string decodificada = Server.HtmlDecode(codificada); //Imagem-com-acentuação.jpg

As you explained in the comments, the file name is already being coded past, so your code would look like this:

string img2 = Server.MapPath(Server.HtmlDecode(codificada));
    
23.05.2018 / 15:02
0

I have seen a code here never class that lists a directory with a comment to "treat paths with accents". When I saw your question, I remembered it and went after it. This is the code (I wrote a path to illustrate):

var path = @"c:\teste\senão\término\um path com textão.txt";
var pathD = path.Normalize(System.Text.NormalizationForm.FormD);

If you look at the value of the two variables, it is apparently the same, testing with path == pathD returns false.

I've read more about the Normalize method and from what I've seen, it changes something in the binary string representation, changing unicode characters. The view is the same, but the comparison (including% w / o%) changes.

Here it works fine with File.Exists . For example I made a fiddle: link

    
23.05.2018 / 14:54