Visual Studio - XML - System.IO.FileNotFoundException

0

I created a new XML file in my project by pressing Ctrl + Shift + A and selected XML File and choosed the name settings.xml.

The file was created under C:\Users\Me\documents\visual studio 2017\Projects\projectname\projectname\settings.xml.

I opened the file in VS and added this content:

<?xml version="1.0"?>
<root>
  <settings name="connectionSettings">
    <updateUrl>Foo</updateUrl>
    <targetUrl>Bar</targetUrl>
  </settings>
</root>

Now I am loading the file into my variable settings:

        XmlDocument settings = new XmlDocument();
        settings.Load("settings.xml");

But I get this error

System.IO.FileNotFoundException occurred
  HResult=0x80070002
  Message=Could not find file 'C:\Users\Me\documents\visual studio 2017\Projects\projectname\projectname\bin\Debug\settings.xml'.

It looks for settings.xml in \bin\Debug. What am I doing wrong?

I was following this tutorial.

c#
visual-studio
asked on Stack Overflow Aug 8, 2017 by Black

3 Answers

3

Since you are not specifying a filepath when loading your settings (just the filename) your application looks in the directory that is 'current' whenit executes (from within VS in Debug mode this will be the 'bin\debug' directory.

first solution:

  • in solution explorer select 'properties' for the file
  • set 'build action' to 'None'
  • set 'Copy to Output Directory' to ' Copy if Newer'

This will copy the most recent version of your 'settings;xml file' to the directory where your application will be executed, where your code will find it. Warning: if you change this file from your code, the changes will not be reflected in te 'master' copy in your solution!

second solution:

  • provide the correct filepath to the settings-file
answered on Stack Overflow Aug 8, 2017 by Johan Donne
1

Try:

settings.Load("..\\..\\settings.xml");

Since you're specifying no path in front of "settings.xml", it uses the current working directory, which is always relative to where the application is running from, which in your case is under bin\Debug.

answered on Stack Overflow Aug 8, 2017 by drone6502 • edited Aug 8, 2017 by Black
0

I noticed that my documentation file (project.xml) was not being copied to the publish folder. I manually copied the file and placed it together with the deployment files and voila the error was resolved.

answered on Stack Overflow Jan 29, 2021 by websplee

User contributions licensed under CC BY-SA 3.0