简体   繁体   English

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

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

I have a web application thet has a number of class library projects. 我有一个Web应用程序,它有许多类库项目。 Some example code below. 下面是一些示例代码。

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

I would normally use Server.MapPath to get the path for the property LenderXml, but when I use it in a class library is returns the path of the parent solution, not that of the class library project. 我通常会使用Server.MapPath来获取属性LenderXml的路径,但是当我在类库中使用它时,它将返回父解决方案的路径,而不是类库项目的路径。

Is there a way of getting the path for the class libary project itself? 有没有办法获得类库项目本身的路径?

Thanks in advance. 提前致谢。

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

希望它有所帮助。

As I can understand you need the current assembly location 据我所知,您需要当前的装配位置

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 will always run in the context of the web root. Server.MapPath将始终在Web根目录的上下文中运行。 So, in your case the web root is the parent web project. 因此,在您的情况下,Web根目录是父Web项目。 While your class libraries (assemblies) look like separate projects, at runtime, they are all hosted in the web project process. 虽然您的类库(程序集)看起来像是单独的项目,但在运行时,它们都在Web项目过程中托管。 So, there are a few things to consider about resources that are in the class libraries. 因此,有关类库中的资源需要考虑的事项。

First, consider if it makes sense to keep resources in the class library. 首先,考虑将资源保留在类库中是否有意义。 Maybe, you should have the xml file in the web project and just reference it in the class library. 也许,您应该在Web项目中使用xml文件,并在类库中引用它。 This would be equivilant to how MVC projects keep their views in the web project. 这与MVC项目如何在Web项目中保持其观点等效。 However, I assume you can't do this. 但是,我认为你不能这样做。

Second, you could change the build properties of your xml file. 其次,您可以更改xml文件的构建属性。 If you change the file to content and copy-always in its properties. 如果将文件更改为contentcopy-always在其属性中进行copy-always The file will copy to the bin directory. 该文件将复制到bin目录。 Then Server.MapPath should work because the file will be accessible. 然后Server.MapPath应该工作,因为该文件是可访问的。

Third, you could make the resource an embedded resource and then reference it in code. 第三,您可以将资源设置为嵌入式资源 ,然后在代码中引用它。 This is a way to keep all the resources local to a built assembly. 这是一种将所有资源保留在构建程序集本地的方法。

Hope this helps. 希望这可以帮助。

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

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