如何在XDocument.Load中使用相对路径?

时间:2021-11-26 07:12:45

I have an XML file named PageData.xml in my App_Data folder. I want to populate an XDocument with this file using XDocument.Load.

我有一个名为PageData的XML文件。我的App_Data文件夹中的xml。我想使用XDocument. load用这个文件填充XDocument。

If I supply the full physical path it works, i.e.:

如果我提供完整的物理路径,它可以工作,即:

XDocument vXDoc = XDocument.Load("/Work/Project/Web/100413 Dev/App_Data/PageData.xml");

...where "Work" is a folder on my C: drive.

…“工作”是我的C:驱动器上的一个文件夹。

If I try a relative path like this, though, I get a DirectoryNotFoundException:

如果我尝试这样的相对路径,我会得到一个DirectoryNotFoundException:

XDocument vXDoc = XDocument.Load("AppData/PageData.xml");

"Could not find a part of the path 'C:\Program Files (x86)\Common Files\Microsoft Shared\DevServer\10.0\AppData\PageData.xml'."

“找不到路径C:\Program Files (x86)\Common Files (Microsoft Shared\DevServer\ DevServer\10.0\AppData\PageData.xml)的一部分”。

This is obviously wrong, but there must be an easy way to set the correct relative path? What am I overlooking? Your help is appreciated.

这显然是错误的,但必须有一个简单的方法来设置正确的相对路径?我俯瞰着什么呢?我是感激你的帮助。

1 个解决方案

#1


21  

There's a couple of ways you can do it. You can use Server.MapPath() to turn a virtual directory into a physical directory path:

有几种方法可以做到。可以使用Server.MapPath()将虚拟目录转换为物理目录路径:

XDocument xdoc = XDocument.Load(Server.MapPath("/App_Data/PageData.xml"));

Or you can use Request.PhysicalApplicationPath as well, like so:

或者你也可以使用Request。物理应用路径也是如此:

var path = Path.Combine(Request.PhysicalApplicationPath, "App_Data\\PageData.xml");
XDocument xdoc = XDocument.Load(path);

In either case, the problem is that the current working directory of the worker process is usually not set to the application directory (this is because working directory is a process-wide property, and a single process can host multiple web sites). More information is here.

在这两种情况下,问题是工作进程的当前工作目录通常不会被设置为应用程序目录(这是因为工作目录是一个进程范围的属性,一个进程可以承载多个web站点)。更多的信息在这里。

#1


21  

There's a couple of ways you can do it. You can use Server.MapPath() to turn a virtual directory into a physical directory path:

有几种方法可以做到。可以使用Server.MapPath()将虚拟目录转换为物理目录路径:

XDocument xdoc = XDocument.Load(Server.MapPath("/App_Data/PageData.xml"));

Or you can use Request.PhysicalApplicationPath as well, like so:

或者你也可以使用Request。物理应用路径也是如此:

var path = Path.Combine(Request.PhysicalApplicationPath, "App_Data\\PageData.xml");
XDocument xdoc = XDocument.Load(path);

In either case, the problem is that the current working directory of the worker process is usually not set to the application directory (this is because working directory is a process-wide property, and a single process can host multiple web sites). More information is here.

在这两种情况下,问题是工作进程的当前工作目录通常不会被设置为应用程序目录(这是因为工作目录是一个进程范围的属性,一个进程可以承载多个web站点)。更多的信息在这里。