How to Handle "ManagementException was Unhandled by user code " Access denied in C#/ Vb.net

108 Views Asked by At

Getting Exception in my code

How to Handle this exception as shown in image

Public Class Form1
Dim processStartEvent As ManagementEventWatcher = New ManagementEventWatcher("SELECT * FROM Win32_ProcessStartTrace")
Dim processStopEvent As ManagementEventWatcher = New ManagementEventWatcher("SELECT * FROM Win32_ProcessStopTrace")

Public Sub New()
    InitializeComponent()
    AddHandler processStartEvent.EventArrived, AddressOf Me.processStartEvent_EventArrived
    processStartEvent.Start()
    AddHandler processStopEvent.EventArrived, AddressOf Me.processStopEvent_EventArrived
    processStopEvent.Start()
End Sub

Private Sub processStartEvent_EventArrived(sender As Object, e As EventArrivedEventArgs)
    Dim processName As String = e.NewEvent.Properties("ProcessName").Value.ToString
    Dim processID As String = Convert.ToInt32(e.NewEvent.Properties("ProcessID").Value).ToString
    FileIO.WriteToFile("+ Process started. Name: " & processName & " | ID: " + processID)
    FileIO.WriteToFile(" | Date & Time: ")
    FileIO.WriteToFile(System.DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"))
End Sub

Private Sub processStopEvent_EventArrived(sender As Object, e As EventArrivedEventArgs)
    Dim processName As String = e.NewEvent.Properties("ProcessName").Value.ToString
    Dim processID As String = Convert.ToInt32(e.NewEvent.Properties("ProcessID").Value).ToString
    FileIO.WriteToFile("- Process stopped. Name: " & processName & " | ID: " + processID)

End Sub End Class

How to handle ManagmentException

1

There are 1 best solutions below

0
On

You get that Exception, because the User the programm is running as has no right to read or execute programms from that folder.

Without telling us what you tried to execute and where it is stored, that is about all we can tell you.