构建 C# 控制台应用程序正在编辑 XML 配置文件并在启动时崩溃应用程序

Building a C# console app is editing an XML config file and crashes application on start up

我正在编写一个控制台应用程序来使用 Dynamics CRM。我已经为应用程序指定了 XML 配置文件,如下所示:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" />
  </startup>
  <configSections>
    <section name="microsoft.xrm.client" type="Microsoft.Xrm.Client.Configuration.CrmSection, Microsoft.Xrm.Client" />
  </configSections>
  <connectionStrings>
    <add name="Xrm" connectionString="Server=XXXX://XXXXXXX:XXXX/XXXX; Domain=XXXXXXX; Username=XXXXXX; Password=XXXXXX" />
  </connectionStrings>
  <microsoft.xrm.client>
    <contexts>
      <add name="Xrm" type="Xrm.XrmServiceContext, Xrm" />
    </contexts>
  </microsoft.xrm.client>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.ServiceBus" publicKeyToken="XXXXXXXX" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-2.5.0.0" newVersion="2.5.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

然而,在构建和 运行 控制台应用程序时,它根本不喜欢 <startup> 标签并崩溃,引发以下错误:

Unhandled Exception: System.Configuration.ConfigurationErrorsException: Configur
ation system failed to initialize ---> System.Configuration.ConfigurationErrorsE
xception: Only one <configSections> element allowed per config file and if prese
nt must be the first child of the root <configuration> element. (C:\Users\admini
strator.XXXX\Desktop\XXXXX\XXXX\XXXXX\XXXXX\XXXXX
XXXXXX.exe.Config line 6)
   at System.Configuration.ConfigurationSchemaErrors.ThrowIfErrors(Boolean ignor
eLocal)
   at System.Configuration.BaseConfigurationRecord.ThrowIfParseErrors(Configurat
ionSchemaErrors schemaErrors)
   at System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey
)
   --- End of inner exception stack trace ---
   at System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey
)
   at System.Configuration.ClientConfigurationSystem.System.Configuration.Intern
al.IInternalConfigSystem.GetSection(String sectionName)
   at Microsoft.Xrm.Client.Configuration.CrmConfigurationManager.CreateProvider(
)
   at System.Lazy`1.CreateValue()
   at System.Lazy`1.LazyInitValue()
   at Microsoft.Xrm.Client.CrmOrganizationServiceContext..ctor(String contextNam
e)
   at Xrm.XrmServiceContext..ctor(String contextName) in C:\Users\XXXXXX\
Desktop\XXXXX\XXXXX\XXXXX\XXXXX\XXXXX\XXXXX\XXXXX\XXX
XXXXXX\Xrm.cs:line 245616
   at XXXXXXXX.consoleApp.Main(String[] args) in C:\Users\XXXXX
\XXXX\XXXXX\XXXXX\XXXXXX\XXXXX\XXXXXXX\XXXXX\XXXXX\XXXX
XXXXX\XXXXX.cs:line 22

所以根据错误定义,我想我应该手动删除启动标记,以便 <configSections> 位于顶部。 运行 它再次起作用(它从 CRM 中获取了我想要的数据)。然而,在做了一些进一步的工作并再次构建应用程序之后,<startup> 标签被自动注入,因此它再次使应用程序崩溃。有没有一种干净的方法来阻止添加 <startup> 标签?

我通过修改与 binobj 文件夹等位于同一目录中的 App 配置文件解决了这个问题

<startup> 标记放入此文件 XML 的最后部分将以相同的方式构建控制台应用程序配置。