Black
Black

Reputation: 20402

Visual Studio - XML - System.IO.FileNotFoundException

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.

Upvotes: 0

Views: 8859

Answers (3)

websplee
websplee

Reputation: 317

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.

Upvotes: 0

drone6502
drone6502

Reputation: 433

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.

Upvotes: 1

Johan Donne
Johan Donne

Reputation: 3285

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

Upvotes: 3

Related Questions