0

我做了一个在 USB 闪存驱动器上写入 txt 文件的方法。目前,我通过绑定到按钮的 RelayCommand 启动该方法。但我想在自动插入 USB 闪存驱动器时启动该方法。因此,此方法会自动将 txt 文件写入插入的闪存驱动器上。(GetDrives 方法将插入的第一个驱动器的驱动器号回复给我)。有谁知道如何实现这一点?

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);
                }
            }
        }

编辑:我不需要已经插入的驱动器。当插入新的 USB 闪存驱动器时,我需要触发我的方法。

4

1 回答 1

2

您可以为此使用 ManagementEventWatcher。
微软上有一篇文章叫做如何检测可移动磁盘,很好地解释了它。我几乎在生产代码中使用了文章中的代码,它适用于 Win7、Win8 和 Win10。

于 2016-02-18T08:19:57.800 回答