简体   繁体   中英

How can I populate back my list with objects read from .txt file? (C# UWP)

I'm not familiar with FileIO in UWP apps, but I managed to save my list to a .txt file with a method I found on this site. The thing is, I have no idea how could I read the file and populate my list with those objects. My object class looks like this:

public class Item : ObservableObjectBase
    {
        private string id;
        public string ID
        {
            get => id;
            set => SetAndNotifyIfChanged(ref id, value);
        }

        private string description;
        public string Description
        {
            get => description;
            set => SetAndNotifyIfChanged(ref description, value);
        }

        private int quantity;
        public int Quantity
        {
            get => quantity;
            set => SetAndNotifyIfChanged(ref quantity, value);
        }

        private Category category;
        public Category Category
        {
            get => category;
            set => SetAndNotifyIfChanged(ref this.category, value);
        }

        private int price;
        public int Price
        {
            get => price;
            set => SetAndNotifyIfChanged(ref price, value);
        }

where Category is:

public class Category : ObservableObjectBase
    {
        private string name;
        public string Name
        {
            get => name;
            set => SetAndNotifyIfChanged(ref name, value);
        }

        private bool isSensitive;
        public bool IsSensitive
        {
            get => isSensitive;
            set => SetAndNotifyIfChanged(ref isSensitive, value);
        }

I managed to save these Item objects to a file like this:

private async void Button_Click_2(object sender, RoutedEventArgs e)
        {
            var sortedLines = itemlist.OrderBy(i => i.ID)
                          .Select(i => $"{i.ID}*{i.Category.ToString()}*{i.Description}*{i.Price.ToString()}*{i.Quantity.ToString()}");

            StorageFolder folder = ApplicationData.Current.LocalFolder;
            StorageFile file = await folder.CreateFileAsync("data.txt", CreationCollisionOption.ReplaceExisting);

            if (file != null)
            {
                await FileIO.WriteLinesAsync(file, sortedLines);
            }
        }

Here I save Category as a string, its overriden ToString method looks like this:

private string IsSensitiveAsString => IsSensitive ? "[S]" : "";
public override string ToString() => $"{Name} {IsSensitiveAsString}";

In the text file I seperated the properties with *, since the description can be long and can contain commas, spaces and what not. After adding 2 items, this is how they appear in the text file:

ABC123*SUV *Item1's description. Contains spaces! *3000*40
DEF456*OldTimer [S]*Item2's description. This one can be really long too!!*5400*82

I'm totally lost about the method I could do this considering it's a UWP app, I could do a single string, but I don't have any idea how could I convert back my Category to its Name and IsSensitive property. Also if the item's description is too long, it can be multiple lines long in the text file and I'm not sure if that would cause some problems. Any help would be greatly appreciated!

How can I populate back my list with objects read from .txt file? (C# UWP)

As @Michał Turczyn said, the better way is serialization the list to JSON string, and retrieve the list object with JSON deserialization.

For Example.

serialization

 var items = new ObservableCollection<string>() { "hee", "ss", "dasde" };
 string output = JsonConvert.SerializeObject(items);

deserialization

 string json = await Windows.Storage.FileIO.ReadTextAsync(file);
 var items = JsonConvert.DeserializeObject<ObservableCollection<string>>(json);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM