How can I use Server.MapPath inside class library project

我只是一个虾纸丫 提交于 2019-12-22 04:07:16

问题


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.


回答1:


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

Hope its helpful.




回答2:


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



回答3:


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.



来源:https://stackoverflow.com/questions/16009891/how-can-i-use-server-mappath-inside-class-library-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!