【问题标题】:Save Settings Or Data C#保存设置或数据 C#
【发布时间】:2012-12-15 06:01:50
【问题描述】:

我是 stackoverflow 的新手,但我认为我应该尝试一下......

所以我要做的是将变量保存在其他程序可以访问的文件中......例如,我有一个设置应用程序来处理所有设置数据(例如数据库信息,字符串、数字或布尔值)。我的想法是将它们保存到像属性文件或文本文件这样的文件中,另一个程序可以读取它们并修改该设置文件。谁能指出我正确的方向?

谢谢 waco001

【问题讨论】:

  • 也许利用更灵活的预定义数据格式并将其存储为 XML。 Plus .NET 有许多用于编写和读取 XML 格式文件的类。

标签: c# properties settings save


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    典型的方法是创建一个XmlDocument,用恰当命名的节点和属性填充它,然后通过Save() 写出来。这样做的好处是,大多数其他环境都能够读取 XML 并对其进行解析。

    另一种“通用语”是 JSON,可以通过 JSON.NET 轻松编写,并且可以被大多数其他环境“理解”。

    【讨论】:

      【解决方案3】:

      如果您使用 C#,我建议您将所有设置放在一个单独的类中,然后使用 XmlSerialization 来保存它,这样您就可以使用最少的代码获得功能,并且您将拥有您的数据以其他应用程序易于阅读的格式保存。

      有多个示例可供选择,例如: http://www.jonasjohn.de/snippets/csharp/xmlserializer-example.htm

      【讨论】:

      【解决方案4】:

      如果您只想在应用程序之间共享数据,您应该研究 WCF。

      或者您可以使用现有的 .NET API for XML 创建和解析数据。然后使用系统IO将其存储到硬盘中。

      【讨论】:

        【解决方案5】:

        创建一个设置类并对其进行序列化/反序列化,如果您将配置封装在不同的对象中,这还有使用属性网格管理它的额外好处,我通常使用我的配置文件来执行此操作,这是一个小例子:

        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
            }
        }
        

        所以要反序列化(_configurationPath是存放config的xml的路径):

                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);
                    }
                } 
        

        并进行序列化:

            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);
        

        希望对你有帮助。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-09-01
          • 1970-01-01
          • 2013-05-05
          • 2023-03-27
          • 1970-01-01
          • 2012-06-29
          • 2012-07-08
          • 2010-11-26
          相关资源
          最近更新 更多