繁体   English   中英

有效检测应用程序是否正在使用文件

[英]Effectively detect if a file is being used by an application

我昨天做了这个问题,但此刻我没有得到任何答案。

无论如何,我的新方法是创建一个小的程序在后台一直运行,并定期检查是否有临时文件未被应用程序使用。

这次,我将在系统临时文件夹中创建一个文件夹来存储打开的文件。

这是代码:

private const uint GENERIC_WRITE = 0x40000000;
private const uint OPEN_EXISTING = 3;

private static void Main()
{
    while (true)
    {
        CleanFiles(Path.GetTempPath() + "MyTempFolder//");
        Thread.Sleep(10000);
    }
}

[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern SafeFileHandle CreateFile(string lpFileName, UInt32 dwDesiredAccess, UInt32 dwShareMode,
                                                IntPtr pSecurityAttributes, UInt32 dwCreationDisposition,
                                                UInt32 dwFlagsAndAttributes, IntPtr hTemplateFile);

private static void CleanFiles(string folder)
{
    if (Directory.Exists(folder))
    {
        var directory = new DirectoryInfo(folder);

        try
        {
            foreach (var file in directory.GetFiles())
                if (!IsFileInUse(file.FullName))
                {
                    Thread.Sleep(5000);
                    file.Delete();
                }
        }
        catch (IOException)
        {
        }
    }
}


private static bool IsFileInUse(string filePath)
{
    if (!File.Exists(filePath))
        return false;

    SafeHandle handleValue = null;

    try
    {
        handleValue = CreateFile(filePath, GENERIC_WRITE, 0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
        return handleValue.IsInvalid;
    }
    finally
    {
        if (handleValue != null)
        {
            handleValue.Close();
            handleValue.Dispose();
        }
    }
}

但这有一个问题:

使用docx和pdf(使用Foxit Reader)文件可以正常工作。

即使记事本仍在使用txt文件,它们也会被删除,但是我可以忍受,因为文件的内容仍在记事本中可见。

真正的问题在于Windows Photo Viewer之类的应用程序。 即使WPV仍在使用图像,这些图像也会被删除,但是这次图像从WPV中消失,并且在屏幕上显示消息Loading...。

我需要一种真正检测应用程序是否仍在使用文件的方法。

你就是不行

“文件被另一个程序使用”没有黑魔法。 这仅表示另一个程序已打开文件的句柄

某些应用程序始终保持打开句柄,而其他应用程序(例如记事本)则始终保持打开状态:打开文件时,记事本打开文件的句柄,借助打开的句柄读取整个文件,关闭该句柄并显示向用户读取字节。

如果删除文件,很好,没有打开的手柄,并且记事本不会每一个都注意到您删除了文件。

请看看这个SO 问题

在这里,您可以按应用名称(更简便的方式)检查应用:

 Process[] pname = Process.GetProcessesByName("notepad");
 if (pname.Length == 0)
    MessageBox.Show("nothing");
 else
    MessageBox.Show("run");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM