简体   繁体   中英

How can I use Server.MapPath inside class library project

I have a web application thet has a number of class library projects. 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.

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. So, in your case the web root is the parent web project. While your class libraries (assemblies) look like separate projects, at runtime, they are all hosted in the web project process. 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. This would be equivilant to how MVC projects keep their views in the web project. However, I assume you can't do this.

Second, you could change the build properties of your xml file. If you change the file to content and copy-always in its properties. The file will copy to the bin directory. Then Server.MapPath should work because the file will be accessible.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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