0

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.

golyo
  • 517
  • 3
  • 12
L4c0573
  • 333
  • 1
  • 7
  • 23
  • 1
    Possible duplicate of [How to detect a USB drive has been plugged in?](http://stackoverflow.com/questions/6003822/how-to-detect-a-usb-drive-has-been-plugged-in) – Jay Feb 18 '16 at 07:53
  • I think this answer show how to find usb drives that are already plugged in. But I want to start my method when an drive get plugged in. – L4c0573 Feb 18 '16 at 07:54
  • The answer is here: http://stackoverflow.com/questions/1783657/get-notification-when-a-new-drive-is-connected-via-usb-or-other-means-c?rq=1 – Ravid Goldenberg Feb 18 '16 at 07:58
  • So you can't listen to WM_DEVICECHANGE (as http://stackoverflow.com/questions/6003822/how-to-detect-a-usb-drive-has-been-plugged-in did not answer your question)... I don't think there are many options left - maybe poll on timer? – Alexei Levenkov Feb 18 '16 at 08:08

1 Answers1

2

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.

Jakob Olsen
  • 793
  • 8
  • 13