简体   繁体   中英

Xamarin Android project can't find XML file

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://docs.microsoft.com/en-us/xamarin/android/platform/files/

Note :There is a sample included in this link which you can refer to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM