I am trying to read a section of a Windows service configuration file and extract a value (port number). Following code works fine on my local machine but not in any server I tested even though the service is installed in exact same folder structure.
On servers, I get "illegal character in path" error (I added a couple of try-catch to see where it dies and what the message was).
public static string GetCurrentTCPPort(){ string sTCPPort = "7899"; string ServiceName = "ABC - Tcp Interface Service"; using (ManagementObject wmiService = new ManagementObject("Win32_Service.Name='" + ServiceName +"'")) { try { wmiService.Get(); } catch (Exception ex) { throw new Exception("Died in GetCurrentTCPPort - wmiService.Get()"); } string ServiceExePath = wmiService["PathName"].ToString(); System.Configuration.Configuration config; try { config = ConfigurationManager.OpenExeConfiguration(ServiceExePath); // FilePath = "C:\\ABC\\APP\\ABC - Tcp Interface Service\\ABC.Service.TcpInterface.exe.config" string[] saLiteningIPs = config.AppSettings.Settings["TcpServerListenIpAddrsAndPortNos"].Value.Split(','); // "1.2.3.4:7899,1.2.3.5:7899" if (saLiteningIPs.Length > 0) { sTCPPort = saLiteningIPs[0].Split(':')[1]; } } catch (Exception ex) { // This exception is thrown string sExcep = string.Format("Died in GetCurrentTCPPort - OpenExeConfiguration(); ServiceExePath: {0}{1}Exception: {2}", ServiceExePath, Environment.NewLine, ex.Message); throw new Exception(sExcep); } } return sTCPPort; }
When I run it, I get:
Died in GetCurrentTCPPort - OpenExeConfiguration(); currentserviceExePath: "C:\ABC\APP\ABC - Tcp Interface Service\ABC.Service.TcpInterface.exe"Exception: An error occurred loading a configuration file: Illegal characters in path.