我编写了程序,需要自己的文件监视器(检查文件是否可以打开的循环)。像这样:
while (loadedFiles.Count > 0 || isNeedReRead)
{
Thread.Sleep(1000);
if (isNeedReRead)
ReadFromRegistry();
foreach (var file in loadedFiles)
{
if (!IsFileLocked(file.Value))
{
// logic
}
}
}
来源:是否有一种方法来检查文件是否正在使用?
这是我的解决方案:
try
{
using (Stream stream = new FileStream(
path, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
stream.Close();
return false;
}
}
catch (IOException)
{
return true;
}
它可以很好地与Word, Excel。但是,如果进程没有锁定文件,则此方法不起作用。例如,如果打开的位图文件正在更改,IsFileLocked
返回false。
任何想法?
您可以通过使用System.IO.FileSystemWatcher设置监视文件,您应该能够使用NotifyFilter属性(设置为LastAccessTime)来检测特定文件的最后访问时间。
void SetupWatcher()
{
// Create a new FileSystemWatcher and set its properties.
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = @"C:";
/* Watch for changes in LastAccess and LastWrite times, and
the renaming of files or directories. */
watcher.NotifyFilter = NotifyFilters.LastAccess;
// Only watch text files.
watcher.Filter = "*.txt";
// Add event handlers.
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
// Begin watching.
watcher.EnableRaisingEvents = true;
}
// Define the event handlers.
private static void OnChanged(object source, FileSystemEventArgs e)
{
// Specify what is done when a file is changed, created, or deleted.
Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
}
private static void OnRenamed(object source, RenamedEventArgs e)
{
// Specify what is done when a file is renamed.
Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath);
}
假设这是windows,另一个选项是枚举每个进程打开的文件句柄列表。这里发布的代码有一个不错的实现,所以你所要做的就是调用
DetectOpenFiles.GetOpenFilesEnumerator(processID);
但是,如果一个进程打开一个文件,将其内容读入内存,然后关闭该文件,那么您将无法摆脱监视选项(上面列出),因为一旦该文件被读入内存,该进程实际上不再打开该文件。