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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7202543/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 15:40:52  来源:igfitidea点击:

how to solve System.TypeInitializationException was unhandled exception in vb.net?

vb.netexception-handlingconsole

提问by Hardy

I have created a vb.net console application when i am running the source code it will work fine.But when i am running the Executable file it is throwing an exeption like "System.TypeInitializationException was unhandled".In my application i have used MCL PrinterMonitorComponent

我在运行源代码时创建了一个 vb.net 控制台应用程序,它可以正常工作。但是当我运行可执行文件时,它会抛出一个类似“System.TypeInitializationException 未处理”的异常。在我的应用程序中,我使用了 MCL打印机监视器组件

my code is:

我的代码是:

 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

if any one know please help me..

如果有人知道请帮助我..

sorry for my bad english

对不起,我的英语不好

回答by herzmeister

Generally, a TypeInitializionExceptionis thrown when another exception happens inside a static constructor.

通常,TypeInitializionException当静态构造函数中发生另一个异常时会抛出 a。

Check for the InnerExceptionproperty of the former, and you will get more information about the actual error.

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

回答by Nana

When I encountered this issue, the exception pointed to a line of code that was actually not related to the configuration item that was missing from the Web.Config file. Basically I was using a Constants.cs file to initialise settings from the Web.config file that were then used in the code. One of these constants was missing from the Web.config file and simply adding this setting to the Web.config file resolved the issue.

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

回答by Kevin M

In my case, this error turned out to be a typo in a read-only local variable. "20017" is not a valid year. Unfortunately, I wasted a lot of time diagnosing. The error message was not helpful.

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

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

回答by Helephant

In my case, it was a console app that was instantiating some static variables from config and the config entries were missing:

就我而言,它是一个控制台应用程序,它从 config 实例化一些静态变量,并且缺少配置条目:

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

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

It never hit the breakpoint inside main because it happened as the class was being instantiated, before it hit the main method.

它从未在 main 中遇到断点,因为它发生在类正在被实例化时,在它遇到 main 方法之前。