Xamarin android数据保存到json文件 [英] Xamarin android data saving to json file
问题描述
我需要在调用方法OnDestroy
时保存文件,并在调用方法OnCreate
时加载同一文件.目前,我可以轻松地从Assets中读取json
文件(效果很好)
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);
,但是当我尝试将(c3)类数据保存(写入)到上面打开的相同文件时,我遇到了一些问题.我试过了:
, 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);
尝试此操作会出现错误
System.UnauthorizedAccessException: Access to the path "/Assets eiksmes.json" is denied.
with this try I get error
System.UnauthorizedAccessException: Access to the path "/Assets eiksmes.json" is denied.
也尝试过:
string data = JsonConvert.SerializeObject(items);
StreamWriter writer = new StreamWriter(Assets.Open("reiksmes.json"));
writer.WriteLine(data);
并通过此尝试我得到错误
System.ArgumentException: Stream was not writable.
摘要:
我想我选择了错误的目录(Assets
),我需要保存和加载数据(json
格式).那么我需要在哪里保存它们以及如何保存(举个例子)?
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)?
推荐答案
您无法将任何内容保存到资产中.您可以从中阅读.您必须将文件保存到其他文件夹.
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);
}
这篇关于Xamarin android数据保存到json文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!