Reputation: 6378
I have found many Articles and Questions about finding an XML file but all of them are for Same Project.
Suppose I have my Project structure as shown below:
ABC <------ Solution
|--ABC.Data <------ Project
| |--XMLFiles <-------Folder
| |--AA.xml
|
|--ABC.Client <------ Project
| |--ViewModels <-------Folder
| |-MainViewModel.cs
Now I would like to load AA.xml file in MainViewModel.cs using XDocument.Load(....path.....)
.
So, how can I get path
?
Upvotes: 1
Views: 3778
Reputation: 867
you need a couple of settings to make your scenario work
first right click the xml file(or any file you want to access) and set 'Copy to Output Directory' to 'Copy Always' and when you build or publish the folder structure of that file(AA.xml in your case) will be created on bin or publish(web project) folder and you have simply have to write this code
var path = HostingEnvironment.ApplicationPhysicalPath+"\\bin";//path to you bin
if you are using winforms
var path = Application.StartupPath;//path to you bin
finally
var fullpath=path+"\\XMLFiles\\AA.xml";
XDocument.Load(fullpath) ;
however the better approach will be to create a Helper Class that will fetch the xml content for you application such as
public static class XMLHelpers
{
public static XMLDocument GetXML(string KEY)
{
string file="";
switch(KEY)
{
case "AA": file=Path.Combine(file,"AA.txt");
break;
}
var xmldoc=new XMLDocument();
xmldoc.Load(file);
return xmldoc;
}
}
Upvotes: 1
Reputation: 148150
You will have to move back from the executing assembly folder on parent of ABC.Data and ABC.Client. For example the executing assembly is located in ABC.Client->ViewModels->Bin->Debug
XDocument.Load("../../../../../ABC.Data/ABC.Data/AA.xml");
But practically I see no use of it as the project hierarchy wont be there when you deploy the application. If you have XML file that need to be accessed by multiple assemblies the simply put that xml file in Execution folder. All the assemblies will be able to access it.
You can also make a separate assembly that exposes the AA.xml file data for read and write for all other projects by adding reference of that assembly to those projects. I would prefer this method.
Upvotes: 1