监视文件何时被使用
Monitor when a file is in use
我需要监控文件 (*.wav) 何时被执行。
我知道 filesystemwatcher class。然而,这个 class 会在文件被使用时发出通知吗?我也遇到了Monitor when an exe is launched。虽然我意识到这与 exe 有关,但有没有办法通知 wav 文件已执行?
不,打开非可执行文件(如 mp3、wav、txt 等)时无法获取事件。
但实际上现在可以检查文件是否打开写...
static void Main(string[] args)
{
using (BackgroundWorker bw = new BackgroundWorker())
{
bw.DoWork += Bw_DoWork;
bw.RunWorkerAsync();
}
Console.WriteLine("Press Q to exit");
while (Console.ReadKey(true).Key!=ConsoleKey.Q){}
}
private static bool[] opened;
private static void Bw_DoWork(object sender, DoWorkEventArgs e)
{
var files = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.mp3");
opened = new bool[files.Length];
while (true)
for (int i = 0; i < files.Length; i++)
try
{
using (var fs = File.Open(files[i], FileMode.Open, FileAccess.Read, FileShare.None))
opened[i] = false;
}
catch{ opened[i] = true; }
}
P.S。我知道这很丑 :D
我需要监控文件 (*.wav) 何时被执行。
我知道 filesystemwatcher class。然而,这个 class 会在文件被使用时发出通知吗?我也遇到了Monitor when an exe is launched。虽然我意识到这与 exe 有关,但有没有办法通知 wav 文件已执行?
不,打开非可执行文件(如 mp3、wav、txt 等)时无法获取事件。
但实际上现在可以检查文件是否打开写...
static void Main(string[] args)
{
using (BackgroundWorker bw = new BackgroundWorker())
{
bw.DoWork += Bw_DoWork;
bw.RunWorkerAsync();
}
Console.WriteLine("Press Q to exit");
while (Console.ReadKey(true).Key!=ConsoleKey.Q){}
}
private static bool[] opened;
private static void Bw_DoWork(object sender, DoWorkEventArgs e)
{
var files = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "*.mp3");
opened = new bool[files.Length];
while (true)
for (int i = 0; i < files.Length; i++)
try
{
using (var fs = File.Open(files[i], FileMode.Open, FileAccess.Read, FileShare.None))
opened[i] = false;
}
catch{ opened[i] = true; }
}
P.S。我知道这很丑 :D