Search code examples
c#pathstatic-methodswebmethod

How to get relative path to static string?


In my Asp.Net page I have one webmethod that sends some data to other page and for this method I have to provide path, something like this:

string Path => Server.MapPath(@"\myPath1");

[System.Web.Services.WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static string GetAvailability()
{
    //xdocDetail = XDocument.Load(Path); //THIS DO NOT WORK, NEEDS STATIC STRING
    xdocDetail = XDocument.Load(@"C:\Users\Eggii\Source\Repos\adm_app3\ADM_App\Content\Xmls\Detail.xml");

    List<DetailList> availabilityList = (from detail in xdocDetail.Descendants("Product")
                                         select new DetailList
                                         {
                                          Detail6 = (string)detail.Element("Availability") ?? "Unknown",
                                         }).ToList();

    return JsonConvert.SerializeObject(availabilityList.Select(x => x.Detail6));
}

But I do not want that ugly full path in my method, is it possible somehow to get relative path to this webmethod? Or some other better solutions?


Solution

  • If your content is stored in your project you could use AppDomain.CurrentDomain.BaseDirectory which contains the application root directory in ASP.NET. This will look like:

    xdocDetail = XDocument.Load(AppDomain.CurrentDomain.BaseDirectory+Path)