Search code examples
c#.netremoting.net-remoting

In C# how do I reference the port number configured in app.exe.config?


In our server, we configure the port in app.config as follows:

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

We then proceed to configure the server with the following C# code:

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

How do I reference the port number after it has been configured short of parsing the file by hand?


Solution

  • Looks like it is possible after all. After calling RemotingConfiguration.Configure(string, bool), I run the following method:

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

    This gives me the TcpChannel info I need, which allows me to grab the ChannelUri and get the port.

    GRAIT SUCCESS!