tags:

views:

292

answers:

1

In a VSTO Excel addin the code:

Dim XMLDoc As XElement = XElement.Load("XMLFile1.xml")

generates a FileNotFound error with the message ("Could not find file 'C:\Users\doug\Documents\XMLFile1.xml'.") It's looking in the My Documents folder but the XML file is located in the VS Projects folder for that project. I have set the XML file's "Copy to Output Directory" property to "Copy always". When I change the code to include the full path to the XML file the code works.

Also, if I include the above code in a Windows Console or other type of project it runs correctly. I'm only getting it in the Excel Addin. The above is true for VSTO 2008/Excel 2003 and VSTO 2010/Excel 2010.

+2  A: 

When you use the relative path, the current directory (Environment.CurrentDirectory) is used to resolve that path. In the case of a VSTO Add-in this is set to the user documents folder automatically. However for a console application that value is set to the same folder as the executable and that is why you are experiencing different behaviors.

If your file will be deployed to the same folder as your VSTO Add-in assembly you can use (AppDomain.CurrentDomain.BaseDirectory) to build the full path to the file.

Example, in C#:

string filename = "XMLFile1.xml";

string path = Path.Combine(
    AppDomain.CurrentDomain.BaseDirectory,
    filename);

XElement.Load(path);
João Angelo
João, thanks very much. That works.
Doug Glancy