繁体   English   中英

如何在类库项目中使用Server.MapPath

[英]How can I use Server.MapPath inside class library project

我有一个Web应用程序,它有许多类库项目。 下面是一些示例代码。

public static class LenderBL
{
    static string LenderXml { get { return "MyPathHere"; } }

    public static LenderColl GetLenders()
    {
        var serializer = new XmlSerializer(typeof(LenderColl));

        using (XmlReader reader = XmlReader.Create(LenderXml))
        {
            return (LenderColl)serializer.Deserialize(reader);
        }
    }
}

我通常会使用Server.MapPath来获取属性LenderXml的路径,但是当我在类库中使用它时,它将返回父解决方案的路径,而不是类库项目的路径。

有没有办法获得类库项目本身的路径?

提前致谢。

    var Mappingpath = System.Web.HttpContext.Current.Server.MapPath("pagename.aspx");

希望它有所帮助。

据我所知,您需要当前的装配位置

static public string CurrentAssemblyDirectory()
{
    string codeBase = Assembly.GetExecutingAssembly().CodeBase;
    UriBuilder uri = new UriBuilder(codeBase);
    string path = Uri.UnescapeDataString(uri.Path);
    return Path.GetDirectoryName(path);
}

Server.MapPath将始终在Web根目录的上下文中运行。 因此,在您的情况下,Web根目录是父Web项目。 虽然您的类库(程序集)看起来像是单独的项目,但在运行时,它们都在Web项目过程中托管。 因此,有关类库中的资源需要考虑的事项。

首先,考虑将资源保留在类库中是否有意义。 也许,您应该在Web项目中使用xml文件,并在类库中引用它。 这与MVC项目如何在Web项目中保持其观点等效。 但是,我认为你不能这样做。

其次,您可以更改xml文件的构建属性。 如果将文件更改为contentcopy-always在其属性中进行copy-always 该文件将复制到bin目录。 然后Server.MapPath应该工作,因为该文件是可访问的。

第三,您可以将资源设置为嵌入式资源 ,然后在代码中引用它。 这是一种将所有资源保留在构建程序集本地的方法。

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM