armandasalmd
armandasalmd

Reputation: 179

Xamarin android data saving to json file

I need to save the file when method OnDestroy is called and load same file when method OnCreate is called. At this time I can read json 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);
items.Add(myList);

, but I have some problems when I try to save(write) Daiktai 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"));
writer.WriteLine(data);

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

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

Upvotes: 1

Views: 6427

Answers (1)

neo
neo

Reputation: 2042

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

        Console.WriteLine(path);
        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);
        }

Upvotes: 1

Related Questions