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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With