我需要將輸入頁面中的資訊保存到 JSON 檔案中,并將資訊輸出到從 JSON 檔案中讀取的另一個頁面上。
我已經嘗試了很多東西,似乎對我有用的是使用特殊檔案夾 localapplication 資料。
現在,我不太明白如何輸出資訊并檢查資料是否正確輸入。
我之前使用 StreamReader 輸出 JSON 檔案的資訊,然后將其放在 ListView 上,但如果我將檔案放在特殊檔案夾中,這將不起作用。它說“流不能為空”。注釋掉的代碼是我之前嘗試過的代碼。
代碼:
ListPageVM(讀取頁面)
private ObservableCollection<MainModel> data;
public ObservableCollection<MainModel> Data
{
get { return data; }
set { data = value; OnPropertyChanged(); }
}
public ListPageVM()
{
var assembly = typeof(ListPageVM).GetTypeInfo().Assembly;
Stream stream = assembly.GetManifestResourceStream(Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "eintraege.json"/"SaveUp.Resources.eintraege.json"/));
//var file = Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "eintraege.json");
using (var reader = new StreamReader(stream))
{
var json = reader.ReadToEnd();
List<MainModel> dataList = JsonConvert.DeserializeObject<List<MainModel>>(json);
data = new ObservableCollection<MainModel>(dataList);
}
}
MainPageVM(寫頁面)
public Command Einfügen
{
get
{
return new Command(() =>
{
// Data ins Json
_mainModels.Add(DModel);
Datum = DateTime.Now.ToString("dd.mm.yyyy");
//var assembly = typeof(ListPageVM).GetTypeInfo().Assembly;
//FileStream stream = new FileStream("SaveUp.Resources.eintraege.json", FileMode.OpenOrCreate, FileAccess.Write);
var file = Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "eintraege.json");
//Stream stream = assembly.GetManifestResourceStream("SaveUp.Resources.eintraege.json");
if (!File.Exists(file))
{
File.Create(file);
}
using (var writer = File.AppendText(file))
{
string data = JsonConvert.SerializeObject(_mainModels);
writer.WriteLine(data);
}
});
}
}
uj5u.com熱心網友回復:
您正在嘗試讀取和寫入資源,而不是檔案。那是行不通的。而是這樣做
var path = Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "eintraege.json");
File.WriteAllText(path, myjson);
讀回資料
var json = File.ReadAllText(path);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/468878.html
標籤:C# xamarin xamarin.forms xamarin.android
上一篇:InvalidOperationException:未找到連接字串
下一篇:相互使用多個Linq查詢
