Using Server.MapPath () inside a static field in ASP.NET MVC

I am creating an ASP.NET MVC site where I use Lucene.Net for search queries. I asked a question here about how to properly structure the use of Lucene.Net in an ASP.NET MVC application and it was said that the best method is to declare my IndexWriter as public static so that it can be reused.

Here is the code that sits at the top of my SearchController:

 public static string IndexLocation = Server.MapPath("~/lucene"); public static Lucene.Net.Analysis.Standard.StandardAnalyzer analyzer = new Lucene.Net.Analysis.Standard.StandardAnalyzer(); public static IndexWriter writer = new IndexWriter(IndexLocation,analyzer); 

Since writer is static, IndexLocation must also be static. Thus, the compiler gives me the following error for Server.MapPath() :

An object reference is required for a non-static field, method or property 'System.Web.Mvc.Controller.Server.get'

Is there a way to use Server.MapPath () or something similar from a static field ? How can I fix this error?

Thanks in advance.

+83
c # static asp.net-mvc server.mappath
Sep 25 '10 at 23:32
source share
2 answers

Try HostingEnvironment.MapPath , which is static .

See this SO question for confirmation that HostingEnvironment.MapPath returns the same value as Server.MapPath : What is the difference between Server.MapPath and HostingEnvironment.MapPath?

+189
Sep 25 '10 at 23:58
source share

I think you can try this for a call from class

  System.Web.HttpContext.Current.Server.MapPath("~/SignatureImages/"); 

* ---------------- Sorry, I tried because the static function has already answered the question with drift *

 System.Web.Hosting.HostingEnvironment.MapPath("~/SignatureImages/"); 

Update

I have an exception when using System.Web.Hosting.HostingEnvironment.MapPath("~/SignatureImages/");

Details: System.ArgumentException: The relative virtual path 'SignatureImages' is not allowed here. in System.Web.VirtualPath.FailIfRelativePath ()

Solution (tested on static web method)

System.Web.HttpContext.Current.Server.MapPath("~/SignatureImages/"); Worked

+28
Oct 26 '13 at 14:22
source share



All Articles