L4c0573
L4c0573

Reputation: 343

Start Method when USB was plugged in [C#]

I made a method that writes a txt file on a usb flash drive. At the moment I start that method via a RelayCommand that is binded to a button. But I want to start that method evertime a usb flash drive is plugged in automatically. So that this method writes the txt-file automatically on the flash drive that is plugged in. (The method GetDrives replys me the driveletter of the first drive that is plugged in). Does anyone know how to realize that?

public void WriteFileOnFDrive()
        {
            var firstDrive = GetDrives().FirstOrDefault();
            if (!string.IsNullOrEmpty(firstDrive))
            {
                string myText = "TestText";
                string path = firstDrive + @"SomeText.txt";
                if (File.Exists(path))
                {
                    Console.WriteLine("SomeText already exists!");
                }
                else
                {
                    System.IO.File.WriteAllText(path, myText);
                    File.SetAttributes(path, File.GetAttributes(path) | FileAttributes.Hidden | FileAttributes.ReadOnly | FileAttributes.System);
                }
            }
        }

Edit: I don´t need the drives that are already plugged in. I need to trigger my method, when a new usb flash drive gets plugged in.

Upvotes: 1

Views: 444

Answers (1)

Jakob Olsen
Jakob Olsen

Reputation: 823

You can use a ManagementEventWatcher for that.
There is an article on Microsoft called How to detect a removable disk that explains it nicely. I am using the code from the article almost as-is in production code, and it works on both Win7, Win8 and Win10.

Upvotes: 3

Related Questions