7

I have a XML file in a folder in the project. I would like to use XDocument.Load(string) but do I have to write the complete path to the application as part of the URI (such as in my example)?

XDocument xml = XDocument.Load("c:/users/myuser/documents/visual studio
2010/Projects/ErrorRegistro/Registro.xml");
Fco
  • 195
  • 1
  • 2
  • 13
  • I think you are either looking for the project path or looking for the assembly path... either way this question may help.. http://stackoverflow.com/q/11218776/2270839 – Kevin Sep 08 '13 at 04:26

2 Answers2

22

Another way that bypass the ressource issue is to add the file to project (same as the ressource solution), then click on the file and in the property tab choose "copy always" in copy to output path. That way the file will get copied to the output directory when you build and it's as simple as doing

 XDocument xml = XDocument.Load("Registro.xml");
Ronan Thibaudau
  • 3,413
  • 3
  • 29
  • 78
  • I rather tend to do "Copy if newer". That's a bit cleaner. – Jurijs Kastanovs Jun 29 '16 at 05:36
  • @JurijsKastanovs It's not "cleaner" it's different. There are cases when you want to copy if not newer (for example if your application modifies the xml file you could launch in debug, do a few changes in visual studio, the app would change the file and on next debug your VS changes would be ignored as the modified date on the target file would be newer deployed than in the solution). It depends on their use case really – Ronan Thibaudau Jun 29 '16 at 12:20
2

It would be better to add your XML file as a project resource: go to the properties of the project then to Resources tab. Choose Add Resource and add your file. Then you will be able to get your XDocument that way:

XDocument xml = XDocument.Parse(Properties.Resources.Registro);

If you want, however, to keep everything like you did you could maybe go with Reflection. See the answer here: How to read embedded resource text file

Community
  • 1
  • 1
Fabien
  • 1,015
  • 2
  • 11
  • 22