Reading XML in C# when file already present in Visual Studio project - c#

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);

Related

How to give path to an text file in Solution using XDocument?

I want to load a xml document Swedish.xml which exists in my solution. How can i give path for that file in Xamarin.android
I am using following code:
var text = File.ReadAllText("Languages/Swedish.txt");
Console.WriteLine("text: "+text);
But i am getting Exception message:
Could not find a part of the path "//Languages/swedish.txt".
I even tried following lines:
var text = File.ReadAllText("./Languages/Swedish.txt");
var text = File.ReadAllText("./MyProject/Languages/Swedish.txt");
var text = File.ReadAllText("MyProject/Languages/Swedish.txt");
But none of them worked. Same exception message is appearing. Build Action is also set as Content. Whats wrong with the path? Thanks in advance.
Just try with this
string startupPath = Path.Combine(Directory.GetParent(System.IO.Directory.GetCurrentDirectory()).Parent.Parent.FullName, "Languages", "Swedish.txt");
var text = File.ReadAllText(startupPath);
Try...
Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments)+"/Languages/Swedish.txt"
If you mark a file as Content Type, it will be included in the app bundle with the path that you are using within your project file. You can inspect the IPA file (it's just a renamed zip) that is created to verify that this is happening.
var text = File.ReadAllText("Languages/Swedish.txt");
should work. The file path is relative to the root of your application. You need to be sure that you are using the exact same casing in your code that the actual file uses. In the simulator the casing will not matter, but on the device the file system is case sensitive, and mismatched casing will break the app.
I've looked into this before and never found any solution to access files in this way. All roads seem to indicate building them as "content" is a dead end. You can however place them in your "Assets" folder and use them this way. To do so switch the "Content" to "AndroidAsset".
After you have done this you can now access the file within your app by calling it via
var filename = "Sweedish.txt";
string data;
using
(var sr = new StreamReader(Context.Assets.Open(code)))
data = sr.ReadToEnd();
....

loading xml document error in c#

I'm trying to load a document with xml in c#
the name of xml file is variable, here is problem...
string filename="test01.xml";
XmlDocument root = new XmlDocument();
root.Load(filename);
the above code give me error: unable to connect to remote server or unable to load
but the following code works
XmlDocument root = new XmlDocument();
root.Load("test01.xml");
why is that?
You can try to specify the whole path (absolute path) to the file (not only the filename).
So instead of writing "test01.xml" you can try to write "C:\[... path to the file here]\test01.xml" and it should work as intended.
If you specify only the file name, the application will probably look for the file in the current directory (value in Environment.CurrentDirectory). I just tested this in a sample application.
It's worth mentioning that if you use FileName property from OpenFileDialog class as a case with 'using variable', it contains PATH to the file (despite its name ;)).
Does your XML contains DTD declaration with URL? Most probably parser tries to resolve it, and fails, because, say, automatic proxy does not accept its request.

Loading resources from another project?

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.

Using embedded file in VS2008 ASP.NET Project

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

How to load from relative path in WPF application?

I'm reading an xml file and want to make it from a relative directory based on the location of the application, similar to ASP.NET with Server.MapPath or using the tilda.
How can you get the relative path in WPF?
WORKS: XDocument xmlDoc = XDocument.Load(#"c:\testdata\customers.xml");
DOES NOT WORK: XDocument xmlDoc = XDocument.Load(#"~\Data\customers.xml");
DOES NOT WORK: XDocument xmlDoc = XDocument.Load(#"~/Data/customers.xml");
XDocument xmlDoc = XDocument.Load(
Path.Combine(
AppDomain.CurrentDomain.BaseDirectory,
#"Data\customers.xml"));
I assume the Data directory is going to get deployed with your app, in the same root directory as your EXE. This is generally safe, except where shadow copying is involved; for example, when you use NUnit to test this code. (With shadow copying, the assemblies that make up your app get copied to a temporary directory, but files like this get left behind.)
Assuming you're not planning to modify customers.xml after deployment, the safest way to handle this is to embed the file as a resource within your assembly.
XDocument xmlDoc = XDocument.Load(#"Data\customers.xml");
OR
XDocument xmlDoc = XDocument.Load(#".\Data\customers.xml");
BTW, this has nothing to do with WPF and everything to do with Windows paths.
Try File.Create("./HiImHere.txt") to see where is the point directory; after that try the path relative to where HiImHere.txt is.

Categories