Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Get file from virtual path

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

like image 691
Xodarap Avatar asked Dec 10 '10 16:12

Xodarap


2 Answers

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);
like image 139
Phil Hunt Avatar answered Oct 08 '22 17:10

Phil Hunt


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.

like image 28
Pauli Østerø Avatar answered Oct 08 '22 15:10

Pauli Østerø