Xamarin Android project can't find XML file - c#

I have a file in my Xamarin Android project called "SaveData.xml". I can't save it in the assets folder because I need to write to it during runtime. I am trying to access it with my LoadXML() function:
XmlDocument doc = new XmlDocument();
XmlDocument saveData = new XmlDocument();
public void LoadXML()
{
saveData.Load("SaveData.xml");
//This bit works fine.
AssetManager assets = this.Assets;
using (StreamReader sr = new
StreamReader(assets.Open("Spices.xml")))
{
doc.Load(sr);
}
}
I've tried reading up on it but all the answers say to just save in assets folder. I can't do that because I need to write to this file and then read it again every time the app starts. I also tried putting it in the resources folder and changing the build action. Is the file path wrong? do I need to save it somewhere else? I'm stumped.
EDIT: Sorry for not being specific. "saveData.Load("SaveData.xml")" Is throwing a file not found exception and I want to know why.
Here is the xml file.
SaveData.xml
<?xml version="1.0" encoding="utf-8" ?>
<list>
<cupboard></cupboard>
<shoppingList></shoppingList>
</list>

Yes, if you need to write to the xml during runtime application, we can't put it into the assets folder as it's read-only.
Besides, when you execute saveData.Load("SaveData.xml"), you're not specifying a target directory, so it's defaulting to the root directory, then it will throw a file not found exception.
So you'll need to write the file to a location you have write access to.
The code below will specify a file in the user's home directory, which will be writeable:
using System.IO;
string backingFile_path = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "SaveData.xml");
For more details, you can check: https://learn.microsoft.com/en-us/xamarin/android/platform/files/
Note:There is a sample included in this link which you can refer to.

Related

Read .xml file from project directory in Xamarin project

I have difficulty in reading the .xml file from Xamarin project. Whenever I debug my code I get below error
Could not find a part of the path "/storage/emulated/0/Xml/SupportedTypes.xml".
Below is the code what I am using
public static void Initialize(ConnectedDeviceCommType type)
{
string fileName = #"Xml\SupportedTypes.xml";
string filePath = Path.Combine(OS.Environment.ExternalStorageDirectory.ToString(), fileName);
try
{
var xml = XDocument.Load(filePath);
}
catch(Exception ex)
{
string st = ex.Message;
}
}
I have read that in some of the blogs that they say the .xml file needs to add to the Asset folder but in my case, I don't have any Asset folder in my project and The project I am trying to load is not an activity as well.
So can you please tell me is there any approach to read XML files directly in XAMARIN?
I finally made it work Thanks to Dimitris.
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/files?tabs=windows
I don't really understand why you want to keep your xml file on your directrory. Because ,if you release your application, you probably won't set up the same directory structure as development. I suggest putting the files in the same folder as the application. Below the code can helps you to access your xml file from directory.
string filePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "SupportedTypes.xml");

Access an XSLT file as resource from same project?

I have an XSLT file that I want to load and use to transform an XML file. I've added the file to the same project as the code that uses it and put it in the "Resources" folder and set the Build Action to "Resource".
This is the code that tries to access the file:
XslCompiledTransform myXslTransform = new XslCompiledTransform();
myXslTransform.Load(#"[projectName];component/Resources/OrderManagement/OrderOverview.xslt");
... where [projectName] is the name of the project. However this doesn't seem to work. I've played around with different paths, but somehow I don't seem to get it right. I'm sure it's just a little thing, but none of the articles I have found on the internet (or here) have helped me.
Can anyone help?
A co-worker has helped me find a solution. We added the resource via the properties of the project, so that I can access its content easily and used the following code.
using (var reader = new StringReader(Resources.OrderOverview)) {
using (XmlReader xmlReader = XmlReader.Create(reader)) {
myXslTransform.Load(xmlReader);
myXslTransform.Transform(fileName, arguments, xmlTextWriter);
}
}
This is very similar to what outcoldman suggested with the subtle difference that the resource is accessed differently.
Change the build action from Resource to Embedded Resource, after this you can do something like
XslCompiledTransform myXslTransform = new XslCompiledTransform();
var assembly = typeof(SomeTypeFromAssemblyWithResource).Assembly;
using (var stream = assembly.GetManifestResourceStream("Resources.OrderManagement.OrderOverview.xslt"))
{
using (var xmlReader = XmlReader.Create(stream))
{
myXslTransform.Load(xmlReader );
}
}
Resource name in dll can be tricky so maybe you want first to know the resource name with Assembly.GetManifestResourceNames. Compiler generates name based on the folder and assembly.

Programmatically Access a File on ASP.NET MVC4

As part of an ASP.NET MVC4 project I need to be able to read from and write to some XML files. I have trouble finding / accessing the files I need.
I've created a demo project to which I've added a folder /Documents containing some XML files.
So in the same project I have a folder /Classes with my class that should read the XML files using XDocument.load().
Here is what I'd like to do (and how I thought it should work):
string path = "/Documents/test.xml"; // Doesn't work
XDocument xml = XDocument.load(path);
However, this doesn't work. Not with "/Documents", "Documents" or "~/Documents".
Supplying the full path works, but not very useful if the website is going to be deployed in other environments.
string path = "D:/Projects/Demo/Demo/Documents/test.xml"; // Works
XDocument xml = XDocument.load(path);
Any suggestions how I can access the files using some kind of relative path?
use Server.MapPath to get the absolute path.
string path = Server.MapPath("/Documents/test.xml");
XDocument xml = XDocument.load(path);
Use HttpContext.Current.Server.MapPath
string path = HttpContext.Current.Server.MapPath("/Documents/test.xml");
Have you tried:
var path = Server.MapPath("/Documents/test.xml");

How to modify by loading and saving the same xml file

I have a problem with modifying xml file when i first load and then save it with same file path and name. Below is my code. The error is "Access to the path C:\MyApp\Web.config is denied. If i change the path of the xdoc.Save to be different from xdoc.Load, then it will be ok. What is your recommandation to solve this problem? If possible, i need to modify the existing xml file(meaning xml file for loading and saving is the same path).
XmlDocument xdoc = new XmlDocument();
xdoc.Load(#"C:\\MyApp\\Web.config");
XmlNode xn = xdoc.SelectSingleNode("//configuration/MyProvider");
XmlElement el = (XmlElement)xn;
el.SetAttribute("defaultProvider", "MyCustomValue");
xdoc.Save(#"C:\\MyApp\\Web.config");
Thanks in advance.
I would expect this to be fine if you have write access to web.config to start with, and if nothing else is using it. (It was certainly fine in a test I just ran.) I suspect it's more likely that another process is already using the file (or the same process but some other code within it), or that you simply don't have write access to the file.

How to load XML file located inside the folder of the application in window phone 7?

I am developing window phone 7 application. I am new to the window phone 7 application. I have added XML file in my project by right clicking the project & selecting the Add -> New Item. I can then easily load the XML file in my application by using the following code
IsolatedStorageFile isfData = IsolatedStorageFile.GetUserStoreForApplication();
XDocument doc = null;
IsolatedStorageFileStream isfStream = null;
if (isfData.FileExists(strXMLFile))
{
isfStream = new IsolatedStorageFileStream(strXMLFile, FileMode.Open, isfData);
doc = XDocument.Load(isfStream);
isfStream.Close();
}
else
{
doc = XDocument.Load(strXMLFile);
isfStream = new IsolatedStorageFileStream(strXMLFile, FileMode.CreateNew, isfData);
doc.Save(isfStream);
isfStream.Close();
}
By using the above code I can perform the read & write operation in my XML file.
But the problem arises when I put my XML file into the folder. My problem is as follows:
I have added one folder named 'XML Files' in my project by right clicking the project name & selecting the Add -> New Folder in the visual studio. Then I have added a XML file into the 'XML Files' Folder by right clciking the folder & selecting the Add->New Item. When I put the XML file into the folder I am not able to Load it in my application. I have also tried with the following statement
isfStream = new IsolatedStorageFileStream("/XML Files/"+strXMLFile, FileMode.Open, isfData);
I am getting error at
doc = XDocument.Load(strXMLFile);
I am getting the error "Cannot find file '/XML Files/A.xml' in the application xap package." What should I do ? How to load the XML file loacted inside folder ? Is anything wrong in my code ? Can you please provide me any code or link through which I can resolve the above issue ?
First, make sure the Build Action for your XML file is set to Content and the Copy to output option is set to Copy if newer (or Copy always). Then, try this:
XDocument doc = XDocument.Load( "XML Files/MyXmlFile.xml" );
Note that there is no leading forward slash (/); I spent a few hours a few days ago stuck on this silly problem.

Categories

Resources