I'm trying to created an UWP application that when launched reads out an xml file and then displays its content in a list. I sort of managed to create a code that should do what I want, but when I run the application it tells me I shouldn't run it synchronous.
I tried many things suggested both on Youtube and Stackoverflow. Right before I posted this, I found this: How to read in an XML file asynchronously?
I believe that got me a step closer, but not there yet.
With the help of a tutorial and the above mentioned stackoverflow I got to this:
public async Task GetCountriesFromFile()
{
XmlReaderSettings settings = new XmlReaderSettings
{
Async = true
};
XmlReader doc = XmlReader.Create("DummyFilepath/Countries.xml", settings);
while (await doc.ReadAsync())
{
if(doc.NodeType == XmlNodeType.Element && doc.Name == "country")
{
if (doc.HasAttributes)
{
var c = new Country()
{
Id = Convert.ToUInt16(doc.GetAttribute("id")),
Name = doc.GetAttribute("name"),
FromY = Convert.ToUInt16(doc.GetAttribute("from")),
ToY = Convert.ToUInt16(doc.GetAttribute("to"))
};
Countries.CountriesList.Add(c);
}
}
}
}
and my pageloaded event:
private async void PageLoaded(object sender, RoutedEventArgs e)
{
GetCountries getCountries = new GetCountries();
await getCountries.GetCountriesFromFile();
}
Ideally it happens before the page is loaded, but I guess it doesn't matter that much when I use bindings.
This now gets me an error:
System.InvalidOperationException: 'Synchronous operations should not be performed on the UI thread. Consider wrapping this method in Task.Run.'
What should I do to fix that? Thanks in advance