在我的解决方案中,我在根目录下的文件夹中有一个静态类.在那个静态类'文件夹中,有一个包含XML文件的子文件夹.所以我有这些文件:
/PartialViews/Header/MyStaticClass.cs
/PartialViews/Header/Config/en-US.xml
/PartialViews/Header/Config/jp-JP.xml
...
Run Code Online (Sandbox Code Playgroud)
我在使用XDocument.Load()这些XML文件时遇到了麻烦.具体来说,我正在尝试从静态构造函数中加载XML文件MyStaticClass.
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");
}
Run Code Online (Sandbox Code Playgroud)
我也尝试过使用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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9324 次 |
| 最近记录: |