【问题标题】:Start Method when USB was plugged in [C#]插入 USB 时的启动方法 [C#]
【发布时间】:2016-02-18 07:49:44
【问题描述】:

我做了一个在 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 闪存驱动器时触发我的方法。

【问题讨论】:

标签: c# wpf usb usb-flash-drive


【解决方案1】:

您可以为此使用 ManagementEventWatcher。
Microsoft 上有一篇名为How to detect a removable disk 的文章很好地解释了这一点。我在生产代码中几乎按原样使用文章中的代码,它适用于 Win7、Win8 和 Win10。

【讨论】:

  • 谢谢,这正是我想要的!
猜你喜欢
  • 2014-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-16
  • 1970-01-01
  • 2012-08-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多