【问题标题】:Save and Load my listview/observablecolletion to txt保存并加载我的 listview/observablecolletion 到 txt
【发布时间】:2019-07-13 16:41:08
【问题描述】:

当我打开和关闭应用程序时,我需要保存和加载一个列表视图/observablecollection。

我在这里和其他地方搜索过,并尝试了一些东西,但似乎没有任何效果。

我已经粘贴了我发现的代码,我认为它可以解决问题。也许它确实有一些变化。

//This one is for adding items, and it works fine.

try
                {

                    Tanknings.Add(new Tankning { Date = Dato.Date.ToString("dd-MM-yyyy"),
                        KmTaeller = KmTaeller.Text,
                        LiterTanket = Math.Round(Convert.ToDouble(LiterTanket.Text), 2).ToString(),
                        Pris = Math.Round(Convert.ToDouble(Pris.Text), 2).ToString(),
                        KmKoert = (Convert.ToInt32(KmTaeller.Text) - Convert.ToInt32(AktuelKmTaeller.Text)).ToString(),
                        PrisPrLiter = Math.Round((Convert.ToDouble(Pris.Text) / Convert.ToDouble(LiterTanket.Text)), 2).ToString(),
                        KmPrLiter = Math.Round(((Convert.ToDouble(KmTaeller.Text) - (Convert.ToDouble(AktuelKmTaeller.Text))) / Convert.ToDouble(LiterTanket.Text)), 2).ToString() });
            }
                catch
                {
                }

//This i what i tried to save and load the items.

private async void saveTankninger()
        {
            XmlSerializer xs = new XmlSerializer(typeof(ObservableCollection<Tankning>));

            using (StreamWriter wr = new StreamWriter("Files/Tankninger.xml"))
            {
                xs.Serialize(wr, Tanknings);
            }

            /* Firstly we will use StorageFolder class from the Windows.Storage namespace
            to get path to the LocalFolder for our application: */
            StorageFolder storageFolder = ApplicationData.Current.LocalFolder;

            /* Then we need to have reference to the file where we can store notes:
            Note that if file exists we do not want to create another one: */
            StorageFile notesFile = await storageFolder.CreateFileAsync("Tankninger.txt", CreationCollisionOption.OpenIfExists);

            // Now we want to serialize list with the notes to save it in the JSON format ine the file:
            var serializedNotesList = JsonConvert.SerializeObject(Tanknings);

            // Last step is to write serialized list with notes to the text file:
            await FileIO.WriteTextAsync(notesFile, serializedNotesList);
        }

        private async void loadTankninger()
        {
            /* Firstly we will use StorageFolder class from the Windows.Storage namespace
            to get path to the LocalFolder for our application: */
            StorageFolder storageFolder = ApplicationData.Current.LocalFolder;

            /* Then we need to have reference to the file where we can store notes:
            Note that if file exists we do not want to create another one: */
            StorageFile notesFile = await storageFolder.CreateFileAsync("Tankninger.txt", CreationCollisionOption.OpenIfExists);

            // Read serialized notes list from the file:
            string serializedNotesList = await FileIO.ReadTextAsync(notesFile);

            // Deserialize JSON list to the ObservableCollection:
            if (serializedNotesList != null)
            {
                Tanknings = JsonConvert.DeserializeObject<ObservableCollection<Tankning>>(serializedNotesList);
                tankningTable.ItemsSource = Tanknings;
            }
        }

【问题讨论】:

  • 您是否有任何特定原因要同时使用 xml 和 json 序列化?或者它们中的任何一个都有效?
  • 不,这只是我在粘贴之前没有删除的又一次尝试!

标签: c#


【解决方案1】:

假设您使用的是 newtonsoft JSON 库并已填充 List

序列化:

using Newtonsoft.Json;

List<Class_name> aList = getListFromSomehwere();
string json = JsonConvert.SerializeObject(aList);
// Do whatever you want with string, e.g. save to file

反序列化:

using Newtonsoft.Json;
string json = ReadFile(); // Your function to read all text from file

List<Class_name> aList = (JsonConvert.DeserializeObject<IEnumerable<Class_name>>(json)).ToList();
// Do whatever you want with this list

要在关闭时保存 - 只需将事件添加到您的应用程序关闭事件、序列化列表并将其保存到文件中。

要在加载时打开 - 添加 window_loaded 事件(或显示的表单或您喜欢的任何内容),读取所有文件,反序列化 json。有很多方法可以解决这个问题,您可以决定要做什么。

编辑:JSON.NET DeserializeObject to List of Objects 可能会有所帮助

【讨论】:

  • 它现在几乎可以工作了。我可以保存一个项目,然后将其重新加载。但它不会向 Listview 添加任何新内容。但它会将“下一个”添加到 .txt 文件中,所以下次我打开它时,它会显示那个。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-14
  • 1970-01-01
相关资源
最近更新 更多