如何在.net windows应用程序中读取不同目录中的xml文件?

时间:2012-06-26 06:39:50

标签: .net xml winforms

我有一个.net windows应用程序我正在尝试从c#windows应用程序中读取.xml文件。

但我收到了错误:

  

无法找到路径'c:\ WindowsFormsApplication1 \ WindowsFormsApplication1 \ bin \ Debug \〜\ Files \ test.xml'的一部分。

但我的文件位于Files文件夹中,该文件夹仅在应用程序WindowsFormsApplication1中 不在\bin\Debug

那么为什么要搜索\bin\Debug

form.cs中的代码

DataSet dsAuthors = new DataSet("authors");
            string filePath = @"~/Files/test.xml";

            dsAuthors.ReadXml(filePath);

还请告诉我有没有办法像在Web应用程序中那样使用Server.MapPath。

我尝试了其他解决方案:

string appPath = Path.GetDirectoryName(Application.ExecutablePath);

            System.IO.DirectoryInfo directoryInfo = System.IO.Directory.GetParent(appPath);
            System.IO.DirectoryInfo directoryInfo2 = System.IO.Directory.GetParent(directoryInfo.FullName);

            string path = directoryInfo2.FullName + @"\Files";

但收到错误: Access to the path is denied.

2 个答案:

答案 0 :(得分:2)

尝试:

        string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Path.Combine("Files", "test.xml"));// @"~/Files/test.xml";

如果不起作用,请确保test.xml将“复制到输出目录”属性设置为“始终复制”。

答案 1 :(得分:0)

使用Server.MapPath

您使用的是相对网址。这不适用于ReadXml。它需要磁盘上的绝对路径。

Server.MapPath将采用您的虚拟路径并为您提供绝对路径。

var fullPath = Server.MapPath("~/Files/test.xml");
dsAuthors.ReadXml(fullPath);

注意:Server.MapPath不验证路径是否实际存在。