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