【问题标题】:How to read xml file in .net windows application in different directory?如何在不同目录的.net windows应用程序中读取xml文件?
【发布时间】:2012-06-26 06:39:50
【问题描述】:

我有一个 .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.

【问题讨论】:

  • \bin\Debug 是在调试模式下启动应用程序时的默认路径。在项目属性中设置起始路径。
  • 您可以更改 test.xml 的设置 - 解决方案中的文件也可以复制到调试文件夹中

标签: .net xml winforms


【解决方案1】:

试试:

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

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

【讨论】:

    【解决方案2】:

    使用Server.MapPath

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

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

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

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

    【讨论】:

    • server.mappath 在 WinForms 应用程序中不可用
    • winforms中不存在路径中~的概念
    • server.mappath 在 WinForms 应用程序中不可用 - 还有其他替代方法吗?
    • 不要使用 ~ 。您的 exe 将始终在您的输出文件夹中运行。从那里指定您的路径。更好的方法是将此 test.xml 复制到输出。假设您没有创建目录结构是自找麻烦。
    猜你喜欢
    • 1970-01-01
    • 2010-10-12
    • 2014-01-10
    • 1970-01-01
    • 2022-08-04
    • 2012-03-09
    • 1970-01-01
    • 2018-02-13
    • 1970-01-01
    相关资源
    最近更新 更多