1

I just started to code a Programm which detects the USB Sticks and this is my current code:

public enum EventType
        {
            Inserted = 2,
            Removed = 3
        }
        static void Main(string[] args){

            ManagementEventWatcher watcher = new ManagementEventWatcher();
            WqlEventQuery query = new WqlEventQuery("SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2 or EventType = 3");

            watcher.EventArrived += (s, e) =>
            {
                string driveName = e.NewEvent.Properties["DriveName"].Value.ToString();
                EventType eventType = (EventType)(Convert.ToInt16(e.NewEvent.Properties["EventType"].Value));

                string eventName = Enum.GetName(typeof(EventType), eventType);

                Console.WriteLine("{0}: {1} {2}", DateTime.Now, driveName, eventName);
            };

            watcher.Query = query;
            watcher.Start();

            Console.ReadKey();


        } 

But everytime i get this error: "System.TypeInitializationException: "The type initializer for 'System.Management.ManagementPath' threw an exception."

And i can not find a solution. And yes i imported System.Management; I would be happy if someone could help me.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
  • I ran your code as-is and had no issues. I ran using VS 2019 Community with .Net Framework 4.7.2 – JayV Apr 02 '21 at 13:03
  • There's probably a whole stack trace with inner exceptions, TypeInitializationException is only the top first one – Simon Mourier Apr 02 '21 at 13:22

1 Answers1

0

This error may be related to trimming, try to turn it off by setting PublishTrimmed to false.

<PropertyGroup>
  <OutputType>Exe</OutputType>
  <TargetFramework>net7.0</TargetFramework>
  // ...
  <PublishTrimmed>true</PublishTrimmed>
</PropertyGroup>
xanhacks
  • 122
  • 2
  • 5