简体   繁体   中英

Save Settings Or Data C#

Im new to stackoverflow but thought I should give its a try...

So what I'm trying to do is to save variables in a file which other programs can access... For example, I have a set-up application that takes care of all the setup data (ex. database information, strings, numbers, or booleans). What I thought was to save them to a file like Properties file or text file where another program could read them and modify that settings file. Could anyone please point me off in a proper direction?

Thanks waco001

If you are working with C#, I would suggesting putting all your settings in a separate class and then use XmlSerialization to save it, that way you'll have functionality working with minimal amount of code, and you'll have your data saved in format easy to read by other applications.

There are multiple samples available how to do it, for example: http://www.jonasjohn.de/snippets/csharp/xmlserializer-example.htm

尝试使用Visual Studio项目中支持的App.config。

Create a settings class and serialize/deserialize it, also if you encapsulate your configuration in a different object this have the added benefit of managing it using a property gird, I usually do this with my configuration files, this is a little example:

using System;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.Collections.Generic;
using System.Runtime.Serialization;

namespace Generate.Test
{
    /// <summary>
    /// The configuration class.
    /// </summary>
    [Serializable, XmlRoot("generate-configuration")]
    public class Configuration : ISerializable
    {
        #region Fields

        private string inputPath  = string.Empty;
        private string outputPath = string.Empty;
        private int    maxCount   = 0;

        #endregion

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="Configuration" /> class.
        /// </summary>
        public Configuration()
        {
        }

        #endregion

        #region Properties
        /// <summary>
        /// Gets or sets the output path.
        /// </summary>
        /// <value>
        /// The output path.
        /// </value>
        [XmlElement("output-path")]
        public string OutputPath
        {
            get { return this.outputPath; }
            set { this.outputPath = value; }
        }

        /// <summary>
        /// Gets or sets the input path.
        /// </summary>
        /// <value>
        /// The input path.
        /// </value>
        [XmlElement("input-path")]
        public string InputPath
        {
            get { return this.inputPath; }
            set { this.inputPath = value; }
        }

        /// <summary>
        /// Gets or sets the max count.
        /// </summary>
        /// <value>
        /// The max count.
        /// </value>
        [XmlElement("max-count")]
        public int MaxCount
        {
            get { return this.maxCount; }
            set { this.maxCount = value; }
        }
        #endregion

        #region ISerializable Members

        /// <summary>
        /// Gets the object data.
        /// </summary>
        /// <param name="info">The info.</param>
        /// <param name="context">The context.</param>
        /// <exception cref="System.ArgumentNullException">thrown when the info parameter is empty.</exception>
        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            if (info == null)
                throw new System.ArgumentNullException("info");

            info.AddValue("output-path", this.OutputPath);
            info.AddValue("input-path", this.InputPath);
            info.AddValue("max-count", this.MaxCount);
        }

        #endregion
    }
}

So to deserialize (_configurationPath is the path of the xml where the config is stored):

        if (File.Exists(_configurationPath))
        {
            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(Configuration));
                Stream        stream     = new FileStream(_configurationPath, FileMode.Open, FileAccess.Read);
                Configuration config     = (Configuration)serializer.Deserialize(stream);

                _inputPath  = config.InputPath;
                _outputPath = config.OutputPath;
                _maxCount   = config.MaxCount;
            }
            catch (Exception exception)
            {
                Console.WriteLine("Error cargando el archivo de configuración '{0}':\n{1}", _configurationPath, exception);
            }
        } 

And to serialize:

    Configuration configuration = new Configuration(); // Create the object

    // Set the values

    configuration.InputPath  = @".\input";
    configuration.OutputPath = @".\output";
    configuration.MaxCount   = 1000;

    // Serialize

    XmlSerializer serializer = new XmlSerializer(typeof(Configuration));
    Stream stream = new FileStream(_configurationPath, FileMode.Open, FileAccess.Write);
    serializer.Serialize(stream, configuration);

Hope it helps.

The typical method would be to create an XmlDocument , fill it with aptly named nodes and attributes and write it out via Save() . This has the advantage, that most other environments are able to read XML and parse it.

Another "lingua franca" is JSON, which can easily be written via JSON.NET and is "understood" by most other environments.

If all you want is share data between applications, you should look into WCF.

Or you can use existing .NET API for XML to both create and parse data. Then use system IO to store it into hard drive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM