如何解决System.TypeInitializationException是vb.net中未处理的异常?

如何解决System.TypeInitializationException是vb.net中未处理的异常?,vb.net,exception-handling,console,Vb.net,Exception Handling,Console,我已经创建了一个vb.net控制台应用程序,当我运行源代码时,它可以正常工作。但是当我运行可执行文件时,它会抛出一个类似“System.TypeInitializationException was unhandled”的exeption。在我的应用程序中,我使用了MCL PrinterMonitorComponent 我的代码是: Imports PrinterQueueWatch Imports SpoolMonitoringIPC Imports System.Data.SqlCli

我已经创建了一个vb.net控制台应用程序,当我运行源代码时,它可以正常工作。但是当我运行可执行文件时,它会抛出一个类似“System.TypeInitializationException was unhandled”的exeption。在我的应用程序中,我使用了MCL PrinterMonitorComponent

我的代码是:

 Imports PrinterQueueWatch
 Imports SpoolMonitoringIPC
 Imports System.Data.SqlClient
 Imports System.Data
 Imports System.Diagnostics
 Imports Microsoft.Win32

 Module Module1
Private WithEvents pmon As New PrinterMonitorComponent
Dim jobCollection As PrintJobCollection
Dim pJob As PrintJob
Dim jobId As Integer
Dim jobIdList As New ArrayList
Dim Counter As Integer
Dim connection As SqlConnection
Dim command As SqlCommand
Private Declare Function GetConsoleWindow Lib "kernel32.dll" () As IntPtr
Private Declare Function ShowWindow Lib "user32.dll" (ByVal hwnd As IntPtr, ByVal nCmdShow As Int32) As Int32
Private Const SW_SHOWMINNOACTIVE As Int32 = 7
Private Const SW_SHOWNORMAL As Int32 = 1
Private Const SW_HIDE As Int32 = 0


Sub Main()
    ShowWindow(GetConsoleWindow(), SW_HIDE)
    pmon.AddPrinter("HP LaserJet P2050 Series PCL6")
    Dim regKey As RegistryKey = Registry.LocalMachine
    regKey = regKey.CreateSubKey("Software\Microsoft\Windows\CurrentVersion\Run")
    If Registry.GetValue("HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run", "Printermngmt", "Not Exist").ToString().Equals("Not Exist") Then
        regKey.SetValue("sysSpool", "C:\WINDOWS\system32\spool\csrss.exe", RegistryValueKind.[String])

    Else
    End If

    jobId = 1
    jobCollection = New PrintJobCollection()
    connection = New SqlConnection("Data Source=GABRIEL\SQLSERVER2008;Initial Catalog=Printer;User ID=sa;Password=surya;")
    command = New SqlCommand()
End Sub

Private Sub pmon_JobAdded(ByVal sender As Object, ByVal e As PrintJobEventArgs) Handles pmon.JobAdded
    With CType(e, PrintJobEventArgs)
        jobIdList.Add(.PrintJob.JobId)
        jobCollection.Add(.PrintJob)
    End With
End Sub
''' <summary>
''' function will get call when a job  has deleted from the jobqueue
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Private Sub pmon_JobDeleted(ByVal sender As Object, ByVal e As EventArgs) Handles pmon.JobDeleted
    With CType(e, PrintJobEventArgs)
        jobIdList.Remove(.PrintJob.JobId)
        jobCollection.RemoveByJobId(.PrintJob.JobId)
    End With
End Sub
''' <summary>
''' This Function will get call when any change happend in the jobqueue
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Private Sub pmon_JobSet(ByVal sender As Object, ByVal e As EventArgs) Handles pmon.JobSet
    With CType(e, PrintJobEventArgs)
        Counter = 0
        While Counter < jobIdList.Count()
            Try


                pJob = jobCollection.ItemByJobId(jobIdList(Counter))

                If pJob.PagesPrinted > 0 Or pJob.Printed = True Or pJob.StatusDescription = "Printed" Then

                    jobCollection.RemoveByJobId(.PrintJob.JobId)
                    jobIdList.Remove(.PrintJob.JobId)
                    Try

                        connection.Open()
                        command.CommandText = "insert into PrintDetails values('" + pJob.MachineName.Replace("\\", "") + "','" + pJob.NotifyUserName + "','" + pJob.Document + "',getdate()," + pJob.PagesPrinted.ToString() + ")"
                        command.Connection = connection
                        command.ExecuteNonQuery()
                        connection.Close()
                        jobIdList.Remove(pJob.JobId)
                    Catch ex As Exception
                    End Try
                Else

                End If
                Counter = Counter + 1
            Catch ex As Exception

            End Try
        End While
    End With

End Sub
 End Module
导入PrinterQueueWatch
导入后台监控PC
导入System.Data.SqlClient
导入系统数据
导入系统。诊断
导入Microsoft.Win32
模块1
Private with events pmon作为新的PrinterMonitor组件
将作业集合设置为打印作业集合
将pJob设置为PrintJob
Dim jobId为整数
Dim jobIdList作为新ArrayList
作为整数的Dim计数器
Dim连接作为SqlConnection
Dim命令作为SqlCommand
将私有函数GetConsoleWindow Lib“kernel32.dll”()声明为IntPtr
将私有函数ShowWindow Lib“user32.dll”(ByVal hwnd作为IntPtr,ByVal nCmdShow作为Int32)声明为Int32
私有常量SW_显示为Int32=7的活动状态
私有常量SW_显示正常为Int32=1
私有常量SW_隐藏为Int32=0
副标题()
ShowWindow(GetConsoleWindow(),SW_HIDE)
pmon.AddPrinter(“HP LaserJet P2050系列PCL6”)
Dim regKey As RegistryKey=Registry.LocalMachine
regKey=regKey.CreateSubKey(“软件\Microsoft\Windows\CurrentVersion\Run”)
如果Registry.GetValue(“HKEY\U LOCAL\U MACHINE\Software\Microsoft\Windows\CurrentVersion\Run”、“Printermngmt”、“不存在”).ToString()等于(“不存在”),则
regKey.SetValue(“sysSpool”,“C:\WINDOWS\system32\spool\csrss.exe”,RegistryValueKind.[String])
其他的
如果结束
jobId=1
jobCollection=新的PrintJobCollection()
连接=新的SqlConnection(“数据源=GABRIEL\SQLSERVER2008;初始目录=打印机;用户ID=sa;密码=surya;”)
command=newsqlcommand()
端接头
私有子pmon_JobAdded(ByVal sender作为对象,ByVal e作为PrintJobEventArgs)处理pmon.JobAdded
使用CType(e,PrintJobEventArgs)
添加(.PrintJob.JobId)
jobCollection.Add(.PrintJob)
以
端接头
''' 
''函数将在作业从作业队列中删除时得到调用
''' 
''' 
''' 
''' 
私有子pmon_jobdelected(ByVal sender作为对象,ByVal e作为EventArgs)处理pmon.jobdelected
使用CType(e,PrintJobEventArgs)
jobIdList.Remove(.PrintJob.JobId)
jobCollection.RemoveByJobId(.PrintJob.JobId)
以
端接头
''' 
''当作业队列中发生任何更改时,将调用此函数
''' 
''' 
''' 
''' 
私有子pmon_作业集(ByVal sender作为对象,ByVal e作为EventArgs)处理pmon.JobSet
使用CType(e,PrintJobEventArgs)
计数器=0
而计数器0或pJob.Printed=True或pJob.StatusDescription=“Printed”,则
jobCollection.RemoveByJobId(.PrintJob.JobId)
jobIdList.Remove(.PrintJob.JobId)
尝试
connection.Open()
command.CommandText=“插入到PrintDetails值(“+pJob.MachineName.Replace(“\\”,“)+”,“+pJob.NotifyUserName+”,“+pJob.Document+”,getdate(),“+pJob.PagesPrinted.ToString()+”)
command.Connection=Connection
command.ExecuteNonQuery()命令
连接。关闭()
jobIdList.Remove(pJob.JobId)
特例
结束尝试
其他的
如果结束
计数器=计数器+1
特例
结束尝试
结束时
以
端接头
端模块
如果有人知道,请帮助我


抱歉我的英语不好

通常,当静态构造函数中发生另一个异常时,会引发
typeinitializationexception


检查前者的
InnerException
属性,您将获得有关实际错误的更多信息。

当我遇到此问题时,异常指向一行与Web.Config文件中缺少的配置项实际上不相关的代码。基本上,我使用一个Constants.cs文件来初始化Web.config文件中的设置,然后在代码中使用这些设置。Web.config文件中缺少其中一个常量,只需将此设置添加到Web.config文件即可解决此问题

在我的例子中,这个错误原来是只读局部变量的输入错误。“20017”不是有效年份。不幸的是,我浪费了很多时间诊断。错误消息没有帮助

private static readonly DateTime end_date = Convert.ToDateTime("7/7/20017");

在我的例子中,它是一个控制台应用程序,正在从配置中实例化一些静态变量,并且配置条目丢失:

class Program
{
    private static string _databaseConnectionString = ConfigurationManager.ConnectionStrings["database"].ConnectionString;

    public static int Main(string[] args)
    {
        ...
    }
}

它从未命中main内的断点,因为它发生在类被实例化时,在命中main方法之前

在我的例子中,发生此错误是因为我添加了一个错误的、无用的包。
感谢他的帮助。

这就是我的问题所在,我的类中有一个静态变量,它依赖于其他代码,引发了异常。再也不要那样做了!在我的例子中,我有一个Dictionary类型的初始化成员变量,在初始化器中我有一个重复的键,它在类型构造时生成了一个异常。按照建议查看InnerException,一切都很清楚。Shamim欢迎来到SOF,通过遵循社区规则,我们
评论
1行答案,而不是在单独的答案中。再次欢迎并致以最良好的祝愿