USB插入时的启动方法[C#]
Start Method when USB was plugged in [C#]
我做了一个在U盘上写入一个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 闪存驱动器时触发我的方法。
您可以为此使用 ManagementEventWatcher。
Microsoft 上有一篇名为 How to detect a removable disk 的文章对此进行了很好的解释。我在生产代码中几乎按原样使用文章中的代码,它适用于 Win7、Win8 和 Win10。
我做了一个在U盘上写入一个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 闪存驱动器时触发我的方法。
您可以为此使用 ManagementEventWatcher。
Microsoft 上有一篇名为 How to detect a removable disk 的文章对此进行了很好的解释。我在生产代码中几乎按原样使用文章中的代码,它适用于 Win7、Win8 和 Win10。