Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Server.MapPath and spaces

I noticed something weird in Server.MapPath(). If I have a folder with a space at the end I get:

HttpException: Failed to map the path.

This works fine: Server.MapPath("/Folder1/Folder2/item.jpg")

This works fine: Server.MapPath("/Folder1/ Folder2/item.jpg")

This works fine: Server.MapPath("/Folder1/Fol der2/item.jpg")

This fails!: Server.MapPath("/Folder1/Folder2 /item.jpg")

Could somebody explain to me why a space at the end fails while a space anywhere else doesn't?

Note: None of the folders exist.

like image 633
MrSoundless Avatar asked Jul 26 '12 08:07

MrSoundless


2 Answers

Because you shouldn't:

Do not end a file or directory name with a space or a period. Although the underlying file system may support such names, the Windows shell and user interface does not. However, it is acceptable to specify a period as the first character of a name. For example, ".temp".

The issue comes from the method FileUtil.IsSuspiciousPhysicalPath(string physicalPath, out bool pathTooLong), which does a compare:

string.Compare(physicalPath, Path.GetFullPath(physicalPath), StringComparison.OrdinalIgnoreCase) != 0;

Path.GetFullPath() will trim trailing spaces from directory and file names (because it calls Path.NormalizePath() which does so), which can be discovered calling Path.GetFullPath(@"C:\Foo \Bar.txt") for example. Since that won't match the original path that contains the spaces, the method will return true thus identifying the path as suspicious, after which Server.MapPath will throw the exception.

like image 56
CodeCaster Avatar answered Oct 17 '22 12:10

CodeCaster


The MapPath method maps the specified relative or virtual path to the corresponding physical directory on the server. The method does not check whether the path it returns is valid or exists on the server. You must use Directory.Exists() or File.Exists() method to check if directory or file already exists.

if (File.Exists(Server.MapPath(file)) 

Furthermore, also know following are invlid characters for the method:

Asterisk (*)
Question mark (?)
Angle brackets (< or >)
Comma (,)
Colon or semi-colon (: or ;)
Single-quote or double-quote (' or ")
Right square bracket (])
Double slashes (// or \)

Hope that helps.

like image 36
mrd Avatar answered Oct 17 '22 10:10

mrd