Пример #1
0
        /// <summary>
        /// Save program options into persistence.
        /// See <seealso cref="LoadOptions"/> to load program options on program start.
        /// </summary>
        /// <param name="settingsFileName"></param>
        /// <param name="vm"></param>
        /// <returns></returns>
        public static bool SaveOptions(string settingsFileName, ConfigViewModel vm)
        {
            try
            {
                XmlWriterSettings xws = new XmlWriterSettings();
                xws.NewLineOnAttributes = true;
                xws.Indent      = true;
                xws.IndentChars = "  ";
                xws.Encoding    = System.Text.Encoding.UTF8;

                // Create a new file stream to write the serialized object to a file
                using (XmlWriter xw = XmlWriter.Create(settingsFileName, xws))
                {
                    // Create a new XmlSerializer instance with the type of the test class
                    XmlSerializer serializerObj = new XmlSerializer(typeof(ConfigViewModel));

                    serializerObj.Serialize(xw, vm);

                    xw.Close(); // Cleanup

                    return(true);
                }
            }
            catch
            {
                throw;
            }
        }
Пример #2
0
        /// <summary>
        /// Save program options into persistence.
        /// See <seealso cref="SaveOptions"/> to save program options on program end.
        /// </summary>
        /// <param name="settingsFileName"></param>
        /// <returns></returns>
        public static ConfigViewModel LoadOptions(string settingsFileName)
        {
            ConfigViewModel loadedViewModel = null;

            if (System.IO.File.Exists(settingsFileName))
            {
                // Create a new file stream for reading the XML file
                using (FileStream readFileStream = new System.IO.FileStream(settingsFileName, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    try
                    {
                        // Create a new XmlSerializer instance with the type of the test class
                        XmlSerializer serializerObj = new XmlSerializer(typeof(ConfigViewModel));

                        // Load the object saved above by using the Deserialize function
                        loadedViewModel = (ConfigViewModel)serializerObj.Deserialize(readFileStream);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.ToString());

                        loadedViewModel = new ConfigViewModel(); // Just get the defaults if serilization wasn't working here...
                    }

                    // Cleanup
                    readFileStream.Close();
                }
            }

            return(loadedViewModel);
        }