I have an ASP.NET project and want to include an XML file inside the project to store some relatively static data. To do this I selected "Add File" from the solution context menu and picked my XML file. Having added this to my project, I then wanted to load the XML from within code. I tried the following:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("MyData.xml");
I also tried:
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load("~/MyData.xml");
But it seems to be looking in the current directory (i.e. my VS2008 directory) and not the project. Am I going about this wrongly? Is there a way to simply reference a resource that’s embedded in the project like this?
The tilde '~' in your second attempt gets evaluated when it is part of a file url set in a control property such as HyperLink.NavigateUrl. If it is just part of a string passed to xmlDocument.Load(), it has to be explicitly evaluated using Server.MapPath("~/MyData.xml")
Alternatively,
You could include the file as an embedded resource. Right click the file in your solution and in the Build Action, select Embedded Resource. In the Copy to Output Directory option, select 'Do not copy'
Here is an example of how to read the file:
var assembly = Assembly.GetExecutingAssembly();
if (assembly != null)
{
var stream = assembly.GetManifestResourceStream("RootProjectNamespace.MyData.xml");
if (stream != null)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(stream);
}
}
Note, you have to prefix the filename with the default namespace of your project. You can find this by right clicking your project, selecting properties and in the Application tab, the Default namespace is at the top.
The steps you followed to add the XML file in your ASP.NET project does not embed in your application it like just another file in your application like our .aspx pages.
you may try
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(Server.MapPath("~/MyData.xml"));
also it would be better keeping such files in App_Data folder
Related
I'm making an application that loads and saves profile nodes to an external xml document in my output directory. It worked fine when I was opening it from my Assets folder but since that is read only (I think) I need to have it read and write from the output directory or another folder.
Like this:
XmlDocument users = new XmlDocument();
users.Load("users.xml");
However I get this error when this code runs:
"System.IO.FileNotFoundException: Could not find file "/users.xml"."
I've ticked the secondary storage permissions but i'm still a bit confused about just referencing a file in the output directory.
Would also appreciate the help for saving too as I assume the same error will occur:
users.DocumentElement.AppendChild(user);
users.Save("users.xml");
Thank you in advance.
In xamarin form you can try this code to load xml file from PCL project.
var assembly = typeof(TestClass).GetTypeInfo().Assembly;
Stream stream = assembly.GetManifestResourceStream(“PrjectName.FileName”);
using (var reader = new System.IO.StreamReader(stream))
{
var serializer = new XmlSerializer(typeof(List<BuildOptions>)); var listData = (List<T>)serializer.Deserialize(reader);
}
I have a problem. Not very big but didn't find any answer.
I want to sore some key value pair in file Data.xml and I have saved it at root level.
When I am trying to use code below.
XDocument xmlDoc = new XDocument();
xmlDoc.Load("Data.xml");
Instead of checking at project root level it is checking for some other location. I tried current directory and environment.current path. But it didn't help.
I don't want to specify full path. Because when application will go live I don't want to change it.
I need to use data.xml so that if values got changed we will just replace the data.xml so get new values.
It's looking in the current directory that the application is running (bin\release or bin\debug). What you want to do is make sure that you have that XML file in your project set to Copy to Output Directory
You may want to prefix the name parameter with Application.StartupPath() for rigidity.
I got my answer from another post.
Click here
Below code can be used.
string dirpath = System.Web.HttpContext.Current.Server.MapPath("~/Data.xml");
XDocument xmlDoc = new XDocument();
xmlDoc.Load(dirpath);
I am creating a class library, and i have created a folder called config in the solution directory. and i placed one xml in the folder.
How to load the xml file in my class functions?
I tried like below, its not loading
XmlDocument contentxml = new XmlDocument();
String configxmlfile = System.AppDomain.CurrentDomain.BaseDirectory.ToString() + "Config\\instruction.xml";
contentxml.Load(configxmlfile);
And I want to bind the xml file with the dll, becuase i am going to upload the dll in another application and i will call my classes from the dll, and my class will look for the xml file information there.
In order to Embed a xml to the assembly
1. Right click the xml file and Select properties
2. In the Properties Pane Set the BuildAction as Embeded resource
So this Xml becomes a embeded resource when the application is compiled
Then you can read the xml from the assembly by the following code
System.Reflection.Assembly _assembly = Assembly.GetExecutingAssembly();
System.IO.Stream _xmlStream = _assembly.GetManifestResourceStream("[[YourNamespace]].[[XMLFileName.xml]]");
System.IO.StreamReader _textStreamReader = new System.IO.StreamReader(_xmlStream);
string xml = _textStreamReader.ReadToEnd();
For example, you can add a "Resource File" to your project and add the xml to this resource file(Resources.resx).
Here is some code for getting the content of the xml(config.xml in my example):
public class Class1
{
public XDocument GetXml()
{
return XDocument.Parse(Resources.config);
}
}
Now, in another project:
MyClassLibrary.Class1 c = new MyClassLibrary.Class1();
var xml = c.GetXml();
I'm trying to load an XML file from a separate project; One of these projects is a game engine, which calls the XML document reader and takes in a path specifying the relative directory to the file.
From Engine
XDocument doc;
try
{
Stream stream = this.GetType().Assembly.GetManifestResourceStream(path);
doc = XDocument.Load(stream);
}
catch
{
doc = XDocument.Load(path);
}
From the other project
string filePath = "Test.xml";
Npc npc = new Npc("somename", 2,filePath);
Test.xml resides in the other project's root directory. The Npc constructor makes a call to a Statistics object constructor, which then calls the method which loads the XDocument. As this is happening, the filePath is simply passed downward through the layers.
I've looked at this, and tried the embedded resource example, which is ultimately what I'm trying to accomplish, and it didn't work for me.
What am I doing wrong, here?
Update
I changed Text.xml to Chronos.Text.xml, as that is where the file resides. In my debugger, I see that the stream simply returns null when I use that as a path:
try
{
Stream stream = this.GetType().Assembly.GetManifestResourceStream("Chronos.Test.xml"); //returns null
doc = XDocument.Load(stream); //Exception thrown
}
catch
{
doc = XDocument.Load(path); //File not found
}
Embeded resources are embeded directly in the executable. Assembly.GetManifestResourceStream() is trying to open a stream on the embeded resource, what you should be providing is the resource name in the following format AssemblyDefaultNamespace.Directory.Filename.
If you are trying to open an XML file from another directory, you will have to provide the full path to XDocument.Load(), or a path relative from your current project output directory pointing to that other directory.
Another solution would be to copy the data from the other project into your project and specify that you want the file to be copied to your output directory.
I have a static class in a folder off root in my solution. In that static class' folder, there's a subfolder containing XML files. So I've got these files:
/PartialViews/Header/MyStaticClass.cs
/PartialViews/Header/Config/en-US.xml
/PartialViews/Header/Config/jp-JP.xml
...
I'm having trouble using XDocument.Load() with those XML files. Specifically, I'm trying to load the XML files from the static constructor of MyStaticClass.
XDocument.Load() can't seem to find the files, however. I've tried all these and none work:
static MyStaticClass()
{
XDocument doc;
// These all throw exceptions relating to directory not found
doc = XDocument.Load("/Config/en-US.xml");
doc = XDocument.Load(#"\Config\en-US.xml");
doc = XDocument.Load("/PartialViews/Header/Config/en-US.xml");
doc = XDocument.Load(#"\PartialViews\Header\Config\en-US.xml");
}
I also tried using Assembly.GetExecutingAssembly().Location and Assembly.GetEntryAssembly().Location before the relative path, but the assembly resolved by Assembly is always a .NET library (because the type is being initialized?).
How can I load the file without changing its location in the solution?
In ASP.NET you should use Server.MapPath() to find all local files.
string relPath = "~/PartialViews/Header/Config/en-US.xml";
string absPath = Server.MapPath(relPath);
XDocument doc = XDocument.Load(absPath);
For .NET web apps use
HttpContext.Current.Server.MapPath("~/"); this will get you the root directory of the executing file.