简体   繁体   中英

Not able to read xml file using c#

I am trying to read a xml file using c#

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'.

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). [courtesy @miltonb]

so below are two solutions.

you can add that file into your VS project. then click on that file in VS go to properties set 'Copy to output directory' -> copy always. 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.

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. 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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