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

时间:2013-06-24 11:47:04

标签: c# process

昨天我做了question,但此刻我没有得到任何答案。

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

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

这是代码:

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(带福昕阅读器)文件一起正常工作。

txt文件即使仍被记事本使用也会被删除,但我可以忍受这种情况,因为文件的内容仍然可以在记事本中看到。

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

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

2 个答案:

答案 0 :(得分:1)

你不能。

“另一个程序使用该文件”没有黑魔法。这只是意味着其他程序已经为文件打开了句柄

有些应用程序会一直打开句柄,其他应用程序(例如记事本)则不会:打开文件时,记事本打开文件句柄,由于打开的句柄读取整个文件,关闭句柄,并将读取的字节显示给用户。

如果您删除该文件,没问题,没有打开的句柄,记事本也不会注意到您删除了该文件。

答案 1 :(得分:0)

请查看此SO question

在这里,您可以通过应用程序名称检查应用程序(更简单的方法):

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