2

I've have an Observable collection containing customer objects:

  public class Customer
  {
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Street { get; set; }
    public string Location { get; set; }
    public string ZipCode { get; set; }
  }

What is the easiest way to dump this out to an XML file so I can read it in later?

Edward Tanguay
  • 189,012
  • 314
  • 712
  • 1,047

1 Answers1

14

XML serialization :

ObservableCollection<Customer> customers = new ObservableCollection<Customer>();
...

XmlSerializer xs = new XmlSerializer(typeof(ObservableCollection<Customer>));
using (StreamWriter wr = new StreamWriter("customers.xml"))
{
    xs.Serialize(wr, customers);
}

To reload the data from the file :

XmlSerializer xs = new XmlSerializer(typeof(ObservableCollection<Customer>));
using (StreamReader rd = new StreamReader("customers.xml"))
{
    customers = xs.Deserialize(rd) as ObservableCollection<Customer>;
}
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
  • could you please tell me how you got it to work, under the StreamWriter("customers.xml") I keep getting an error message saying "Argument 1: cannot convert from 'string' to 'System.IO.Stream'" – Dark Templar Jul 20 '16 at 14:21
  • @DarkTemplar which platform are you targeting? The `StreamWriter` constructor that accepts the filename isn't supported on all platform; you might need to open the file some other way and manually pass the `Stream` to the `StreamWriter` – Thomas Levesque Jul 20 '16 at 15:52
  • I'm targeting UWP, I looked in google for how to do this in uwp and couldn't find anything – Dark Templar Jul 20 '16 at 18:41
  • @DarkTemplar [Create/read/write file in UWP](https://msdn.microsoft.com/en-us/windows/uwp/files/quickstart-reading-and-writing-files), [extension methods](https://msdn.microsoft.com/en-us/library/system.io.windowsruntimestorageextensions(v=vs.110).aspx) to get a .NET stream for a `IStorageFile` – Thomas Levesque Jul 20 '16 at 23:45
  • Yes I've tried that, what I don't understand is how to create a file in uwp using xml serializer, I keep getting that error. – Dark Templar Jul 21 '16 at 05:10