我的解决方案中的根目录下的文件夹中有一个静态类。在该静态类的文件夹中,有一个包含 XML 文件的子文件夹。所以我有这些文件:
/PartialViews/Header/MyStaticClass.cs
/PartialViews/Header/Config/en-US.xml
/PartialViews/Header/Config/jp-JP.xml
...
我在对那些 XML 文件使用 XDocument.Load()
时遇到问题。具体来说,我正在尝试从 MyStaticClass
的静态构造函数加载 XML 文件。
XDocument.Load()
似乎找不到文件。我已经尝试了所有这些但都没有用:
static MyStaticClass()
{
XDocument doc;
// These all throw exceptions relating to directory not found
doc = XDocument.Load("/Config/en-US.xml");
doc = XDocument.Load(@"\Config\en-US.xml");
doc = XDocument.Load("/PartialViews/Header/Config/en-US.xml");
doc = XDocument.Load(@"\PartialViews\Header\Config\en-US.xml");
}
我也尝试在相对路径前使用 Assembly.GetExecutingAssembly().Location
和 Assembly.GetEntryAssembly().Location
,但程序集由 Assembly 解析
始终是 .NET 库(因为正在初始化类型?)。
如何在不更改文件在解决方案中的位置的情况下加载文件?
最佳答案
在 ASP.NET 中,您应该使用 Server.MapPath() 来查找所有本地文件。
string relPath = "~/PartialViews/Header/Config/en-US.xml";
string absPath = Server.MapPath(relPath);
XDocument doc = XDocument.Load(absPath);
关于c# - 在 ASP.NET 和 XDocument.Load 中获取文件路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3712032/