21

FTP 操作を実行する ac# .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");
4

3 に答える 3

9

私の推奨するソリューションは、XDocument を使用します。私はそれをテストしていないので、わずかな問題があるかもしれませんが、これは私の主張を示すためです.

public Dictionary<string, string> GetSettings(string path)
{

  var document = XDocument.Load(path);

  var root = document.Root;
  var results =
    root
      .Elements()
      .ToDictionary(element => element.Name.ToString(), element => element.Value);

  return results;

}

次の形式の xml から要素名と値を含む辞書を返します。

<?xml version="1.0" encoding="utf-8"?>
<root>
  <hostname>QA_hostname</hostname>
  <username>QA_username</username>
</root>

全体的に簡潔であるため、このソリューションは素晴らしいと思います。

繰り返しますが、これがそのまま正確に機能するとは思っていません。XAttributes や XElements などを使用すると、これを元のようにすることができます。濾しやすくなります。

于 2014-01-16T20:57:09.313 に答える