打开Windows服务配置文件提示“路径中存在非法字符”报错如何解决?
读取Windows服务配置文件时报路径非法字符问题
问题场景
读取Windows服务配置文件指定区段提取端口号的代码在本地运行完全正常,但在文件夹结构完全一致的测试服务器部署服务后全部运行失败,服务器运行时抛出「路径中存在非法字符」错误,经多组try-catch定位后确认了报错位置与信息。
原始问题代码
public static string GetCurrentTCPPort() { string sTCPPort = "7899"; string ServiceName = "IDC - 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:\\IDC\\APP\\IDC - Tcp Interface Service\\IDC.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) { string sExcep = string.Format("Died in GetCurrentTCPPort - OpenExeConfiguration(); ServiceExePath: {0}{1}Exception: {2}", ServiceExePath, Environment.NewLine, ex.Message); throw new Exception(sExcep); } } return sTCPPort; }
报错信息
Died in GetCurrentTCPPort - OpenExeConfiguration(); currentserviceExePath: "C:\IDC\APP\IDC - Tcp Interface Service\IDC.Service.TcpInterface.exe" Exception: An error occurred loading a configuration file: Illegal characters in path.
配置文件位置截图

根因说明
通过WMI查询Win32_Service获取的PathName属性值,当服务执行文件路径包含空格时,系统会自动为路径包裹双引号,而双引号属于Windows路径非法字符,传入ConfigurationManager.OpenExeConfiguration方法时就会触发路径非法报错。
修复后可运行代码
public static string GetCurrentTCPPort() { string sTCPPort = "7899"; string ServiceName = "IDC - 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(); // 新增以下两行代码修复问题 List<char> invalidPathChars = Path.GetInvalidPathChars().ToList(); invalidPathChars.ForEach(c => ServiceExePath = ServiceExePath.Replace(c.ToString(), String.Empty)); System.Configuration.Configuration config; try { config = ConfigurationManager.OpenExeConfiguration(ServiceExePath); string[] saLiteningIPs = config.AppSettings.Settings["TcpServerListenIpAddrsAndPortNos"].Value.Split(','); if (saLiteningIPs.Length > 0) { sTCPPort = saLiteningIPs[0].Split(':')[1]; } } catch (Exception ex) { string sExcep = string.Format("Died in GetCurrentTCPPort - OpenExeConfiguration(); ServiceExePath: {0}{1}Exception: {2}", ServiceExePath, Environment.NewLine, ex.Message); throw new Exception(sExcep); } } return sTCPPort; }
内容的提问来源于stack exchange,提问作者NoBullMan
相关产品推荐
相关产品推荐

