Process.start中的System.NullReferenceException

时间:2012-11-22 15:52:03

标签: c# .net configuration-files

我有一个使用Process.Start来执行exe的应用程序。它适用于我测试的所有.exe,除非.exe有一个配置文件,它获取一个连接字符串,当发生这种情况时,我得到一个System.NullReferenceException。这是我的代码。

执行exe:

string eucApp = @"C:\Temp\app.exe"
startInfo = new ProcessStartInfo(eucApp);
using (Process execProcess = Process.Start(startInfo))
{
    execProcess.WaitForExit();
}

然后exe启动,第一件事就是获得一个带有此代码行的连接字符串

strCadena = ConfigurationManager.ConnectionStrings("ConnectionString")

如果我用这样的连接字符串替换它,它可以正常工作

strCadena = "Data Source=HostName;Initial Catalog=MyDB;Integrated security=True"

我会删除配置文件并将其值放入.exe代码,但问题是我有超过500个使用配置文件的.exe,所以如果有人知道避免这种情况的方法,请告诉我!

1 个答案:

答案 0 :(得分:1)

感谢您的帮助。我解决了这个问题。不知何故,.exe指向启动过程的aplication的app.config。我将此类添加到VB .Net中开发的.exe

Imports System.Configuration
Imports System.Reflection
Public Class AppConfig
  Implements IDisposable
  Public Shared Function Change(ByVal path As String) As AppConfig

    Return New ChangeAppConfig(path)
  End Function
  Public Overridable Sub Dispose() Implements IDisposable.Dispose
  End Sub
  Private Class ChangeAppConfig
    Inherits AppConfig
    Private ReadOnly oldConfig As String = AppDomain.CurrentDomain.GetData("APP_CONFIG_FILE").ToString
    Private disposedValue As Boolean
    Public Sub New(ByVal path As String)
      AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", path)
      ResetConfigMechanism()
    End Sub
    Public Overrides Sub Dispose()
      If (Not disposedValue) Then
        AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", oldConfig)
        ResetConfigMechanism()
        disposedValue = True
      End If
      GC.SuppressFinalize(Me)
    End Sub
    Private Shared Sub ResetConfigMechanism()

      GetType(ConfigurationManager).GetField("s_initState", BindingFlags.NonPublic Or BindingFlags.Static).SetValue(Nothing, 0)
      GetType(ConfigurationManager).GetField("s_configSystem", BindingFlags.NonPublic Or BindingFlags.Static).SetValue(Nothing, Nothing)
      Dim assemblies() As Type = GetType(ConfigurationManager).Assembly.GetTypes()
      For Each assembly As Type In assemblies
        If (assembly.FullName = "System.Configuration.ClientConfigPaths") Then
          assembly.GetField("s_current", BindingFlags.NonPublic Or BindingFlags.Static).SetValue(Nothing, Nothing)
          Exit For
        End If
      Next
    End Sub
  End Class
End Class

我在程序开始时调用Change函数

AppConfig.Change(Application.StartupPath & "\app.exe.Config")

这样就需要正确的配置文件