armandasalmd armandasalmd - 1 year ago 356
JSON Question

Xamarin android data saving to json file

I need to save the file when method

is called and load same file when method
is called. At this time I can read
file easily from Assets (this works fine)

StreamReader reader = new StreamReader(Assets.Open("reiksmes.json"));
string JSONstring = reader.ReadToEnd();
Daiktai myList = JsonConvert.DeserializeObject<Daiktai>(JSONstring);

, but I have some problems when I try to save(write)
class data to the same file I opened above. I tried:

string data = JsonConvert.SerializeObject(items);
File.WriteAllText("Assets\\reiksmes.json", data);

with this try I get error
System.UnauthorizedAccessException: Access to the path "/Assets
eiksmes.json" is denied.

also tried:

string data = JsonConvert.SerializeObject(items);
StreamWriter writer = new StreamWriter(Assets.Open("reiksmes.json"));

and with this try I get error
System.ArgumentException: Stream was not writable.

I think I chose bad directory(
), I need to save and load data (
format). So where do I need to save them and how(give example)?

neo neo
Answer Source

You can't save anything to assets. You can just read from it. You have to save the file to a different folder.

        var fileName = "reiksmes.json";
        string documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); // Documents folder
        var path = Path.Combine(documentsPath, fileName);

        if (!File.Exists(path))
            var s = AssetManager.Open(fileName);
            // create a write stream
            FileStream writeStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
            // write to the stream
            ReadWriteStream(s, writeStream);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download