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