简体   繁体   English

无法使用C#读取xml文件

[英]Not able to read xml file using c#

I am trying to read a xml file using c# 我正在尝试使用C#读取xml文件

XmlDocument doc = new XmlDocument();
doc.Load(@"/Rules/AssessmentRule.xml");
XmlNode node = doc.SelectSingleNode("/RuleName");
string URI = node.InnerText;
return URI;

I kept breakpoints in 2nd and 3rd line. 我在第二和第三行保留了断点。 I get error in the line below 我在下面的行中收到错误

doc.Load(@"/Rules/AssessmentRule.xml");

It says 它说

Could not find a part of the path 'C:\\Program Files\\Rules\\AssessmentRule.xml'. 找不到路径“ C:\\ Program Files \\ Rules \\ AssessmentRule.xml”的一部分。

The folder structure of my project is, it is having the Rules folder in the same place as my class file 我项目的文件夹结构是,与我的班级文件位于同一位置,其中包含“规则”文件夹

When running in debug the path is based from Debug settings, which defaults to bin\\debug unless you access the file with full path it will be relative to that folder(bin\\debug). 在debug中运行时,该路径基于Debug设置,默认情况下为bin \\ debug,除非您使用完整路径访问该文件,该文件将相对于该文件夹(bin \\ debug)。 [courtesy @miltonb] [礼貌@miltonb]

so below are two solutions. 所以下面是两个解决方案。

you can add that file into your VS project. 您可以将该文件添加到VS项目中。 then click on that file in VS go to properties set 'Copy to output directory' -> copy always. 然后在VS中单击该文件,转到属性集“复制到输出目录”->始终复制。 then just need to give the file name 然后只需要提供文件名

or you get your project directory like this 或者您得到这样的项目目录

string projectPath = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
string xmlLocation = @"Rules/AssessmentRule.xml";
String fullPath = Path.Combine(projectPath,xmlLocation);

If the file in your project folder Try this code for path 如果项目文件夹中的文件,请尝试使用此代码获取路径

string wanted_path = Path.GetDirectoryName(Path.GetDirectoryName(System.IO.Directory.GetCurrentDirect‌​ory()));

then find the file on that path. 然后在该路径上找到文件。

在调试中运行时,该路径基于“ bin \\ debug”,除非您使用完整路径访问该文件,该路径将相对于该文件夹。

You need to get the project directory, then append the xml path. 您需要获取项目目录,然后附加xml路径。

string projectPath = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;
string xmlLocation = @"Rules/AssessmentRule.xml";
String fullPath = Path.Combine(projectPath,xmlLocation);

You should probably use an OpenFileDialog instead. 您可能应该改用OpenFileDialog It'll make your life a lot easier: 这将使您的生活更加轻松:

var openFile = new Microsoft.Win32.OpenFileDialog() {
    CheckFileExists = true,
    CheckPathExists = true,
    Filter = "XML File|*.xml"
};

if (openFile.ShowDialog() ?? false)
{
    XmlDocument doc = new XmlDocument();
    doc.Load(openFile.FileName);
    XmlNode node = doc.SelectSingleNode("/RuleName");
    string URI = node.InnerText;

    return URI;
}
else
{
    // User clicked cancel
    return String.Empty;
}

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

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