【问题标题】:How to get relative path to static string?如何获取静态字符串的相对路径?
【发布时间】:2018-03-16 20:25:50
【问题描述】:

在我的 Asp.Net 页面中,我有一个将一些数据发送到其他页面的 webmethod,对于此方法,我必须提供路径,如下所示:

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

但是我不希望我的方法中有那个丑陋的完整路径,是否有可能以某种方式获得此 webmethod 的相对路径?还是其他更好的解决方案?

【问题讨论】:

    标签: c# path static-methods webmethod


    【解决方案1】:

    如果您的内容存储在您的项目中,您可以使用AppDomain.CurrentDomain.BaseDirectory,它包含 ASP.NET 中的应用程序根目录。这看起来像:

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

    【讨论】:

    • 但是如果项目中没有存储内容怎么办? @Max Mokrousov
    • @Eggii,你说的内容没有存储在项目中是什么意思?路径是相对于某物还是总是硬编码?如果它始终是硬编码的,那么除了存储完整路径之外别无他法。但是,我建议将路径存储在 web.config 中,您将能够在不更改代码的情况下更改路径。
    猜你喜欢
    • 2010-09-21
    • 2013-07-07
    • 2020-07-03
    • 1970-01-01
    • 2022-08-17
    • 1970-01-01
    • 2015-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多