C# 如何在类库项目中使用Server.MapPath
我有一个web应用程序,它有许多类库项目。下面是一些示例代码C# 如何在类库项目中使用Server.MapPath,c#,asp.net,server.mappath,C#,Asp.net,Server.mappath,我有一个web应用程序,它有许多类库项目。下面是一些示例代码 public static class LenderBL { static string LenderXml { get { return "MyPathHere"; } } public static LenderColl GetLenders() { var serializer = new XmlSerializer(typeof(LenderColl)); using
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);
}
}
}
我通常会使用Server.MapPath来获取属性LenderXml的路径,但在类库中使用它时,is返回父解决方案的路径,而不是类库项目的路径
有没有办法获取类库项目本身的路径
提前谢谢
var Mappingpath = System.Web.HttpContext.Current.Server.MapPath("pagename.aspx");
希望对您有所帮助。
Server.MapPath
将始终在web根目录的上下文中运行。因此,在您的例子中,web根是父web项目。虽然类库(程序集)看起来像独立的项目,但在运行时,它们都托管在web项目流程中。因此,对于类库中的资源,有一些事情需要考虑。
首先,考虑是否将资源保存在类库中是有意义的。也许,您应该将
xml
文件放在web项目中,并在类库中引用它。这相当于MVC项目如何在web项目中保留其视图。但是,我想你不能这么做
其次,您可以更改xml
文件的构建属性。如果将文件的属性更改为内容
和始终复制
。该文件将复制到bin目录。然后,Server.MapPath
应该可以工作,因为该文件可以访问
第三,您可以将资源设置为一个,然后在代码中引用它。这是一种将所有资源保持在已生成程序集本地的方法
希望这有帮助。据我所知,您需要当前的装配位置
static public string CurrentAssemblyDirectory()
{
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
return Path.GetDirectoryName(path);
}
需要引用System.Web库,而不仅仅是指定的。@自由职业者-抱歉,也许我的问题不清楚。我可以访问类库中的Server.MapPath,无论它如何返回父项目的路径。我正在寻找类库项目的路径。这一点也不能回答问题。@GrantThomas OP说
Server.MapPath
正在工作,但返回父项目的路径。我只能假设父项目意味着web项目托管。这三个选项都是从被引用库中的代码引用xml文件内容的方法。从我的理解来看,这是一个完全合理的答案。这是我发现的唯一一个在类库和web应用程序中都有效的解决方案。非常感谢。