Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map the physical file path in asp.net mvc

I am trying to read an XSLT file from disk in my ASP.Net MVC controller. What I am doing is the following:

string filepath = HttpContext.Request.PhysicalApplicationPath; filepath += "/Content/Xsl/pubmed.xslt"; string xsl = System.IO.File.ReadAllText(filepath); 

However, half way down this thread on forums.asp.net there is the following quote

HttpContext.Current is evil and if you use it anywhere in your mvc app you are doing something wrong because you do not need it.

Whilst I am not using Current, I am wondering what is the best way to determine the absolute physical path of a file in MVC? For some reason (I don't know why!) HttpContext doesn't feel right for me.

Is there a better (or recommended/best practice) way of reading files from disk in ASP.Net MVC?

like image 256
Phaedrus Avatar asked May 14 '10 14:05

Phaedrus


2 Answers

string filePath = Server.MapPath(Url.Content("~/Content/Xsl/")); 

I disagree with the idea that HttpContext.Current is "evil." It's not the hammer for every problem, but it is certainly better than, e.g., Session for stuff that it can do OK.

like image 116
Craig Stuntz Avatar answered Oct 04 '22 18:10

Craig Stuntz


If you're using WebApi or not specifically within a controller class, you can use the following as an alternative:

HostingEnvironment.MapPath("/Content/Xsl/pubmed.xslt") 
like image 42
raider33 Avatar answered Oct 04 '22 20:10

raider33