7

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.?)

2 Answers 2

19

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

string absFile = Server.MapPath(file);

or

string absFile = HttpContext.Current.Server.MapPath(file);
Sign up to request clarification or add additional context in comments.

Comments

6

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.