Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I read the contents of a file in ASP.Net MVC?

Tags:

asp.net-mvc

I have an ASP.Net MVC controller action that needs to return a json result (it's actually jsonp, but that's not important) that contains the contents of another html file. So basically, I want to do this:

[JsonpFilter]
public JsonResult GetHeader()
{
    var html = System.IO.File.ReadAllText("/htm/external/header.htm");

    return Json(new { html = html }, JsonRequestBehavior.AllowGet);
}

However, it's not finding the right file. It's looking in the C directory (Could not find a part of the path 'C:\htm\external\header.htm'), when I want it to look at the server's root (plus /htm/external, of course).

How can I read this file in? It's externally available, so I guess I could make a separate web request for it, but it seems like I should be able to target it directly.

like image 439
Mike Pateras Avatar asked Dec 04 '12 21:12

Mike Pateras


1 Answers

You can resolve a virutal path to its physical location using the HttpServerUtility.MapPath Method:

string html = System.IO.File.ReadAllText(HttpContext.Current.Server.MapPath("~/htm/external/header.htm"));
like image 102
JamieSee Avatar answered Oct 20 '22 04:10

JamieSee