简体   繁体   English

获取ASP.NET和XDocument.Load中的文件路径

[英]Getting file path in ASP.NET and XDocument.Load

I have a static class in a folder off root in my solution. 在我的解决方案中,我在根目录下的文件夹中有一个静态类。 In that static class' folder, there's a subfolder containing XML files. 在那个静态类'文件夹中,有一个包含XML文件的子文件夹。 So I've got these files: 所以我有这些文件:

/PartialViews/Header/MyStaticClass.cs
/PartialViews/Header/Config/en-US.xml
/PartialViews/Header/Config/jp-JP.xml
...

I'm having trouble using XDocument.Load() with those XML files. 我在使用XDocument.Load()和那些XML文件时遇到了麻烦。 Specifically, I'm trying to load the XML files from the static constructor of MyStaticClass . 具体来说,我正在尝试从MyStaticClass的静态构造函数加载XML文件。

XDocument.Load() can't seem to find the files, however. XDocument.Load()似乎无法找到这些文件。 I've tried all these and none work: 我已经尝试过所有这些但没有工作:

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

I also tried using Assembly.GetExecutingAssembly().Location and Assembly.GetEntryAssembly().Location before the relative path, but the assembly resolved by Assembly is always a .NET library (because the type is being initialized?). 我也尝试使用Assembly.GetExecutingAssembly().LocationAssembly.GetEntryAssembly().Location的相对路径之前,但解决了装配Assembly始终是一个.NET库(因为类型被初始化?)。

How can I load the file without changing its location in the solution? 如何在不更改解决方案中的位置的情况下加载文件?

In ASP.NET you should use Server.MapPath() to find all local files. 在ASP.NET中,您应该使用Server.MapPath()来查找所有本地文件。

string relPath = "~/PartialViews/Header/Config/en-US.xml";
string absPath = Server.MapPath(relPath);

XDocument doc = XDocument.Load(absPath);

For .NET web apps use HttpContext.Current.Server.MapPath("~/"); 对于.NET Web应用程序,使用HttpContext.Current.Server.MapPath("~/"); this will get you the root directory of the executing file. 这将获得执行文件的根目录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM