/// <summary> /// Writes the data for this export to the file specified. /// </summary> /// <param name="filename">The file to write to.</param> /// <param name="geographyProvider">The geography data provider.</param> /// <param name="booksReadProvider">The books data provider.</param> /// <param name="errorMessage">The error message if unsuccessful.</param> /// <returns>True if written successfully, false otherwise.</returns> public bool WriteToFile( string filename, IGeographyProvider geographyProvider, IBooksReadProvider booksReadProvider, out string errorMessage) { errorMessage = string.Empty; try { // Set up the nations file. NationsFile nationsFile = new NationsFile(); foreach (Nation nation in geographyProvider.Nations.OrderBy(x => x.Name)) { nationsFile.Nations.Add(nation); } // Serialize the XML XmlSerializer xmlSerializer = new XmlSerializer(typeof(NationsFile)); TextWriter textWriter = new StreamWriter(filename, false, Encoding.Default); //overwrite original file xmlSerializer.Serialize(textWriter, nationsFile); // Tidy up textWriter.Close(); } catch (Exception e) { errorMessage = e.ToString(); return(false); } return(true); }
/// <summary> /// Reads the data for this import from the file specified. /// </summary> /// <param name="filename">The file to read from.</param> /// <param name="errorMessage">The error message if unsuccessful.</param> /// <returns>True if read successfully, false otherwise.</returns> public bool ReadFromFile(string filename, out string errorMessage) { errorMessage = string.Empty; // Check the file exists. if (!File.Exists(filename)) { errorMessage = $"File {filename} does not exist"; return(false); } // Try to deserialize the nations file. try { using (FileStream file = new FileStream(filename, FileMode.Open, FileAccess.Read)) { // Create the serializer. XmlSerializer xmlSerializer = new XmlSerializer(typeof(NationsFile)); // Try to read the nations file. NationsFile nationsFile = xmlSerializer.Deserialize(file) as NationsFile; if (nationsFile == null) { errorMessage = $"File {filename} could not be deserialized"; return(false); } ImportedItems.Clear(); // Add the items to the list. foreach (Nation nation in nationsFile.Nations) { ImportedItems.Add(nation); } } } catch (Exception e) { errorMessage = e.ToString(); return(false); } return(true); }