开发者

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


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);


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜