【问题标题】:In C# how do I reference the port number configured in app.exe.config?在 C# 中如何引用 app.exe.config 中配置的端口号?
【发布时间】:2011-09-22 14:48:23
【问题描述】:

在我们的服务器中,我们在 app.config 中配置端口如下:

<configuration>
   <system.runtime.remoting>
      <application>
         <channels>
            <channel ref="tcp" port="1234" />
         </channels>
      </application>
   </system.runtime.remoting>
</configuration>

然后我们继续使用以下 C# 代码配置服务器:

RemotingConfiguration.Configure(string.Format("{0}{1}", appFolder, "app.exe.config"), false);

配置完不手动解析文件后如何引用端口号?

【问题讨论】:

    标签: c# .net remoting .net-remoting


    【解决方案1】:

    看来这毕竟是可能的。调用 RemotingConfiguration.Configure(string, bool) 后,我运行以下方法:

    private string GetPortAsString()
              {
                 // Parsing
                 System.Runtime.Remoting.Channels.IChannel[] channels = System.Runtime.Remoting.Channels.ChannelServices.RegisteredChannels;
                 foreach (System.Runtime.Remoting.Channels.IChannel c in channels)
                 {
                    System.Runtime.Remoting.Channels.Tcp.TcpChannel tcp = c as System.Runtime.Remoting.Channels.Tcp.TcpChannel;
                    if (tcp != null)
                    {
                       System.Runtime.Remoting.Channels.ChannelDataStore store = tcp.ChannelData as System.Runtime.Remoting.Channels.ChannelDataStore;
                       if (store != null)
                       {
                          foreach (string s in store.ChannelUris)
                          {
                             Uri uri = new Uri(s);
                             return uri.Port.ToString(); // There should only be one, and regardless the port should be the same even if there are others in this list.
                          }
                       }
                    }
                 }
    
                 return string.Empty;
              }
    

    这为我提供了我需要的 TcpChannel 信息,这使我能够获取 ChannelUri 并获取端口。

    成功!

    【讨论】:

    • 我也想这是一个类似的过程来获取其他连接类型,希望这个信息可以帮助其他人
    【解决方案2】:

    您只能通过代码或配置进行配置,不能同时进行。这意味着您无法通过代码访问配置的详细信息(无需自己传递 xml 文件)。

    【讨论】:

    • 这是不正确的,如有必要,我一直通过代码覆盖 app.config 中的设置,并且我知道如何提取配置文件中设置的其他配置设置。我只是对 System.Runtime.Remoting 不太熟悉。
    • 是的,我也是。远程配置类都是内部的,无法通过我知道的代码访问配置的设置。看看here
    • 啊,你的意思是 Remoting 命名空间它都是内部的。我以为你在概括。
    • 不,我的意思是专门远程处理,看看反射器。
    【解决方案3】:

    我刚刚查看了ConfigurationManager 以帮助获取您需要的值...不幸的是,它看起来不像 system.runtime.remoting 的 sectionGroup:即,此调用失败:

    var cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
    var sectionGroup = cfg.GetSectionGroup("system.runtime.remoting");
    

    所以在我看来,您不能使用框架中现有的任何东西来很好地提取它。我不确定为什么这个 sectionGroup 在代码中不存在。

    【讨论】:

    • 它在 RemotingXmlConfigFileData 中,甚至有它自己的解析器。都是内部的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-26
    • 2010-11-21
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 2011-01-30
    • 1970-01-01
    相关资源
    最近更新 更多