配置文件 INI? XML?其他?

Configuration File INI? XML? Other?

我目前在一个学区工作,我们正在尝试为我们的工具包创建一个 C# exe。我们是 C# 的新手,正在学习它,但由于它的灵活性而想使用它。 C# 工具包将用于使用我们选择的设置、程序、Regedit 更改和首选项自动设置新的或重新映像的计算机。

我们有一个在 powershell 中硬编码的工作版本,我们正在将其转移到 c#。

我们目前的问题是如何使用 settings/config 文件(例如 ini 或 xml)从函数和变量中提取通用信息并填充它们。这样我们就可以创建我们可以 select 和 运行 的通用配置文件。例如:

[Server]
IP=172.1.0.10
Port=9999
PathToCSV=\c:\Files.csv
[Client]
RestartComputerAfterScript=1
Install.Browser.Firefox=1
Install.Browser.Chrome=1
Install.Java=0
Install.PrinterLogic=1
SysConfig.TempLoc=d:\TEMP

此 ini 文件将从我们的 C# GUI select编辑并填充:

  1. 脚本 运行 使用值 1
  2. 后计算机将重新启动
  3. 将使用值 1 安装 Firefox
  4. Java 不会 使用值 0 等安装

我们最终也会尝试传入其他变量,例如注册表路径和值等。

有没有人对我们如何使用 INI 有任何建议,或者对创建构建配置文件有更好的建议?

我研究过的资源: 伊尼: https://www.codeproject.com/Articles/1966/An-INI-file-handling-class-using-C

.Net 框架有一个 ConfigurationManager class 专为此目的而设计的..

摘录:

XML

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <startup> 
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
  </startup>
  <appSettings>
    <add key="Setting1" value="May 5, 2014"/>
    <add key="Setting2" value="May 6, 2014"/>
  </appSettings>
</configuration>

代码:

using System;
using System.Configuration;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            ReadAllSettings();
            ReadSetting("Setting1");
            ReadSetting("NotValid");
            AddUpdateAppSettings("NewSetting", "May 7, 2014");
            AddUpdateAppSettings("Setting1", "May 8, 2014");
            ReadAllSettings();
        }

        static void ReadAllSettings()
        {
            try
            {
                var appSettings = ConfigurationManager.AppSettings;

                if (appSettings.Count == 0)
                {
                    Console.WriteLine("AppSettings is empty.");
                }
                else
                {
                    foreach (var key in appSettings.AllKeys)
                    {
                        Console.WriteLine("Key: {0} Value: {1}", key, appSettings[key]);
                    }
                }
            }
            catch (ConfigurationErrorsException)
            {
                Console.WriteLine("Error reading app settings");
            }
        }

        static void ReadSetting(string key)
        {
            try
            {
                var appSettings = ConfigurationManager.AppSettings;
                string result = appSettings[key] ?? "Not Found";
                Console.WriteLine(result);
            }
            catch (ConfigurationErrorsException)
            {
                Console.WriteLine("Error reading app settings");
            }
        }

        static void AddUpdateAppSettings(string key, string value)
        {
            try
            {
                var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                var settings = configFile.AppSettings.Settings;
                if (settings[key] == null)
                {
                    settings.Add(key, value);
                }
                else
                {
                    settings[key].Value = value;
                }
                configFile.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
            }
            catch (ConfigurationErrorsException)
            {
                Console.WriteLine("Error writing app settings");
            }
        }
    }
}

另一种选择是使用 Settings

如果您愿意接受其他文件格式,我会使用 JSON,因为它简单易用。

使用精彩的图书馆Newtonsoft.Json:

模态 类:

class Server
{
    public string IP { get; set; }
    public int Port { get; set; }
    public string PathToCSV { get; set; }
}

class Client
{
    public bool RestartComputerAfterScript { get; set; }
    public List<string> Install { get; set; }
    public string TempLoc { get; set; }
}

class Config
{
    public Server ServerConfig { get; set; }
    public Client ClientConfig { get; set; }
}

config.json:

{
    "ServerConfig": {
        "IP": "172.1.0.10",
        "Port": 9999,
        "PathToCSV": "C:\Files.csv"
    },
    "ClientConfig": {
        "RestartComputerAfterScript": true,
        "Install": [
            "Firefox",
            "Chrome",
            "PrinterLogic"
        ],
        "TempLoc": "D:\TEMP"
    }
}

从磁盘读取文件:

public static Config Read(string path)
{
    return JsonConvert.DeserializeObject<Config>(System.IO.File.ReadAllText(path));
}

保存配置文件:

public static void Write(string path, Config config)
{
    System.IO.File.WriteAllText(path, JsonConvert.SerializeObject(config, Formatting.Indented));
}

出于一致性考虑,我个人更喜欢在 XML 中使用我的配置,或者在 JSON 中使用网络应用程序。
INI 格式确实提供的一件事是它也可供非技术人员阅读。

不过,如果您对使用 INI 格式感兴趣,那么我建议您试试我的 INI library。它可以简化您处理 INI 文件的任务。
此外,我建议您查看解析和映射功能,简而言之,它们将使您能够将“0”值映射为 "false",将“1”值映射为 "true",然后您就可以从您的 INI 密钥中检索布尔类型的这些值。请参阅以下示例:

IniFile ini = new IniFile();
ini.Load(@"C:\Files\Sample.ini");

ini.ValueMappings.Add("0", false);
ini.ValueMappings.Add("1", true);

IniSection section = ini.Sections["Client"];

bool installChrome;
section.Keys["Install.Browser.Chrome"].TryParseValue(out installChrome);

bool installJava;
section.Keys["Install.Java"].TryParseValue(out installJava);

Console.WriteLine(installChrome);
Console.WriteLine(installJava);