Take the 2-minute tour ×

For various reasons, in development I occasionally want to intercept a request for, say, ~/MyStyle.css

What I want to do is make the following snippet work:

string absFile = VirtualPathUtility.ToAbsolute(file);
return System.IO.File.ReadAllText(absFile);

This absolute path is absolute for the webserver though, it's not going to map to "C:\whatever". Is there an equivalent method to go to the file system? (Or a ReadFromVirtualPath etc.?)

share|improve this question

2 Answers 2

up vote 13 down vote accepted

Use Server.MapPath() to get the file system path for a requested application path.

string absFile = Server.MapPath(file);


string absFile = HttpContext.Current.Server.MapPath(file);
share|improve this answer

You can also use the OpenFile method on VirtualPathProvider to get a Stream pointing at your file

var stream = HostingEnvironment.VirtualPathProvider.OpenFile(file);
var text = new StreamReader(stream).ReadToEnd();

Generally this approach is preferable since you can now, at a later point implement a VirtualPathProvider where, lets say all your css files where located in a database.

share|improve this answer

Your Answer


