Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Server.MapPath issue?

So I am reading a book about asp.net security. and one of the sections there was : how to prevent directory traversal filename ( hacked filenames).

so the line of code was :

string fullPath = Server.MapPath(System.IO.Path.Combine(@"d:\inetpub\inbound\",filename));

but then I noticed the result of the combine which will be :

d:\inetpub\inbound\myfile.txt

But I remember that the parameter type should be virtual path and not filesystem path !

enter image description here

d:\inetpub\inbound\myfile.txt is not a virtual path!

what am I missing ?

enter image description here

p.s. this is the book : (wrox)

enter image description here

like image 318
Royi Namir Avatar asked Dec 01 '25 18:12

Royi Namir


2 Answers

The code sample is wrong.

The role of Server.MapPath is indeed to transform a virtual path into a physical one. If you already have a physical path, there'a no need for Server.MapPath.

The code will probably throw an Exception with the message:

'd:\inetpub\inbound\myfile.txt' is a physical path, but a virtual path was expected.

like image 82
Cristian Lupascu Avatar answered Dec 03 '25 07:12

Cristian Lupascu


You must use Server.MapPath to convert a virtual path (i.e., a path inside your website) to a physical path (such as D:\InetPub\...).

So you can do this:

var physicalPath = Server.MapPath("~/Incoming/Receivedfile.txt");

and then you can use physicalPath to actually access the file.

BTW the tilde in the filename above represents the root of the website the code is running under.

like image 32
Roy Dictus Avatar answered Dec 03 '25 07:12

Roy Dictus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!