4

问题历史:
现在我使用Windows Media Player SDK 9在我的桌面应用程序中播放 AVI 文件。它在 Windows XP 上运行良好,但是当我尝试在 Windows 7 上运行它时,我发现了一个错误 -我无法在播放后立即删除 AVI 文件。问题是存在打开的文件句柄。在 Windows XP 上,我在播放文件期间打开了 2 个文件句柄,它们在关闭播放窗口后关闭,但在 Windows 7 上,我在播放文件期间已经打开了 4 个句柄,其中 2 个在播放窗口关闭后保留。它们只有在关闭应用程序后才会免费。

问题:
我该如何解决这个问题?如何删除已打开句柄的文件?可能存在“强制删除”之类的东西吗?

4

4 回答 4

3

The problem is that you're not the only one getting handles to your file. Other processes and services are also able to open the file. So deleting it isn't possible until they release their handles. You can rename the file while those handles are open. You can copy the file while those handles are open. Not sure if you can move the file to another container, however?

Other processes & services esp. including antivirus, indexing, etc.

Here's a function I wrote to accomplish "Immediate Delete" under Windows:

bool DeleteFileNow(const wchar_t * filename)
{
    // don't do anything if the file doesn't exist!
    if (!PathFileExistsW(filename))
        return false;

    // determine the path in which to store the temp filename
    wchar_t path[MAX_PATH];
    wcscpy_s(path, filename);
    PathRemoveFileSpecW(path);

    // generate a guaranteed to be unique temporary filename to house the pending delete
    wchar_t tempname[MAX_PATH];
    if (!GetTempFileNameW(path, L".xX", 0, tempname))
        return false;

    // move the real file to the dummy filename
    if (!MoveFileExW(filename, tempname, MOVEFILE_REPLACE_EXISTING))
    {
        // clean up the temp file
        DeleteFileW(tempname);
        return false;
    }

    // queue the deletion (the OS will delete it when all handles (ours or other processes) close)
    return DeleteFileW(tempname) != FALSE;
}
于 2011-01-04T18:52:36.460 回答
1

MoveFileEx从技术上讲,您可以通过使用和传入来删除锁定的文件MOVEFILE_DELAY_UNTIL_REBOOT。当lpNewFileName参数为NULL时,Move变成delete,可以删除锁定的文件。但是,这适用于安装人员,除其他问题外,还需要管理员权限。

于 2011-01-04T18:58:16.360 回答
0

您是否检查过哪个应用程序仍在使用 avi 文件?您可以使用handle.exe来做到这一点。您可以在关闭正在使用该文件的进程后尝试删除/移动该文件。

另一种解决方案是使用应用程序unlocker(它是免费的)。

上述两种方法之一应该可以解决您的问题。

于 2011-01-04T18:49:53.023 回答
0

您是否已经尝试要求 WMP 释放句柄?(IWMPCore::close似乎是这样做的)

于 2011-01-04T18:50:06.990 回答