How can I use Server.MapPath inside class library project

做~自己de王妃 提交于 2019-12-05 02:38:42
    var Mappingpath = System.Web.HttpContext.Current.Server.MapPath("pagename.aspx");

Hope its helpful.

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

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.

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