gpt4 book ai didi

c# - 读取外部配置文件

转载 作者:可可西里 更新时间:2023-11-01 03:13:46 25 4
gpt4 key购买 nike

我有一个执行 FTP 操作的 c# .Net 控制台应用程序。目前,我在自定义配置部分指定设置,例如

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="ftpConfiguration" type="FileTransferHelper.FtpLibrary.FtpConfigurationSection, FileTransferHelper.FtpLibrary" />
</configSections>

<ftpConfiguration>
<Environment name="QA">
<sourceServer hostname="QA_hostname"
username="QA_username"
password="QA_password"
port="21"
remoteDirectory ="QA_remoteDirectory" />
<targetServer downloadDirectory ="QA_downloadDirectory" />

</Environment>
</ftpConfiguration>

</configuration>

我想在命令行中指定一个外部配置文件。

然而!!!...

我刚刚意识到上面的“FtpConfiguration”部分并不真正属于应用程序的 app.config。我的最终目标是我将有许多计划任务来执行我的控制台应用程序,如下所示:

FileTransferHelper.exe -c FtpApplication1.config
FileTransferHelper.exe -c FtpApplication2.config
...
FileTransferHelper.exe -c FtpApplication99.config

因此,我相信我走错了路,我真正想要的是在我的自定义 xml 文档中读取的内容,但继续使用 System.Configuration 来获取值...而不是读取 XmlDocument 和序列化它以获取节点/元素/属性。 (不过,如果有人能给我一些简单的代码,我并不反对后者)

不胜感激。谢谢。

更新:我接受的答案是指向另一个 StackOverflow 问题的链接,在此处用我的代码重复 - 下面正是我正在寻找的 - 使用 OpenMappedExeConfiguration 打开我的外部配置文件

ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap();
configFileMap.ExeConfigFilename = @"D:\Development\FileTransferHelper\Configuration\SampleInterface.config";

Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);

FtpConfigurationSection ftpConfig = (FtpConfigurationSection)config.GetSection("ftpConfiguration");

最佳答案

如果您想使用 System.Configuration 打开您的自定义文件,您可能需要查看此帖子: Loading custom configuration files 。 Oliver 以一种非常直接的方式解决了这个问题。

由于您想通过命令行读取传递给您的应用程序的参数,您可能需要访问此 MSDN 帖子: Command Line Parameters Tutorial .

如果您更愿意使用自定义方法,可以通过几种方法来实现。一种可能性是实现一个加载器类,并使用您的自定义配置文件。

例如,假设一个简单的配置文件如下所示:

spec1.config

<?xml version="1.0" encoding="utf-8"?>
<Settings>
<add key="hostname" value="QA_hostname" />
<add key="username" value="QA_username" />
</Settings>

一个非常简单的类似哈希表(键值对)的结构。

一个实现的解析器/阅读器看起来像这样:

        private Hashtable getSettings(string path)
{
Hashtable _ret = new Hashtable();
if (File.Exists(path))
{
StreamReader reader = new StreamReader
(
new FileStream(
path,
FileMode.Open,
FileAccess.Read,
FileShare.Read)
);
XmlDocument doc = new XmlDocument();
string xmlIn = reader.ReadToEnd();
reader.Close();
doc.LoadXml(xmlIn);
foreach (XmlNode child in doc.ChildNodes)
if (child.Name.Equals("Settings"))
foreach (XmlNode node in child.ChildNodes)
if (node.Name.Equals("add"))
_ret.Add
(
node.Attributes["key"].Value,
node.Attributes["value"].Value
);
}
return (_ret);
}

与此同时,您仍然可以使用 ConfigurationManager.AppSettings[]阅读原文app.config文件。

关于c# - 读取外部配置文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21171894/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com