0

I'm working on an UWP application where a user can input data which is placed in a listview. All fine and dandy, but how can I save the user data to a separate file and load it the next time a user boots up the app?

I've tried to find a solution, but I had great difficulty to understand these code snippets and on how to apply these (since I'm fairly new to C# and App development). Would somebody like to explain how I can achieve the saving/loading of the data and explain what the code does?

Thanks in advance! :)

Wesley Lomax
  • 2,067
  • 2
  • 20
  • 34
Rick
  • 3
  • 3

2 Answers2

0

You can create a file like this:

  StorageFile ageFile = await local.CreateFileAsync("Age.txt", CreationCollisionOption.FailIfExists);

I can read and write to a file like this:

StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder; 
var ageFile = await local.OpenStreamForReadAsync(@"Age.txt"); 
// Read the data. 
using (StreamReader streamReader = new StreamReader(ageFile)) 
{
      //Use like a normal streamReader
}

if you are trying to write, use OpenStreamForWriteAsync;
Seth Kitchen
  • 1,526
  • 19
  • 53
0

If I understood well, you have some kind of object structure that serves as a model for your ListView. When the application is started, you want to read a file where the data is present. When closing the application (or some other event) write the file with the changes done. Right?

1) When your application is loaded / closed (or upon modifications or some event of your choice), use the Windows.Storage API to read / write the text into the file.

2) If the data you want to write is just a liste of strings, you can save this as is in the file. If it is more complicated, I would recommend serializing it in JSON format. Use JSON.NET to serialize (object -> string) and deserialize (object <- string) the content of your file and object structure.

Product product = new Product();
product.Name = "Apple";
...
string json = JsonConvert.SerializeObject(product);
Timothée Bourguignon
  • 2,190
  • 3
  • 23
  • 39