如何删除已打开句柄的文件? [英] How to remove the file which has opened handles?

查看:1100
本文介绍了如何删除已打开句柄的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题历史

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

PROBLEM HISTORY:
Now I use Windows Media Player SDK 9 to play AVI files in my desktop application. It works well on Windows XP but when I try to run it on Windows 7 I caught an error - I can not remove AVI file immediately after playback. The problem is that there are opened file handles exist. On Windows XP I have 2 opened file handles during the playing file and they are closed after closing of playback window but on Windows 7 I have already 4 opened handles during the playing file and 2 of them remain after the closing of playback window. They are become free only after closing the application.

问题:

我如何解决这个问题? 如何删除已打开句柄的文件?可能存在类似强制删除的内容?

QUESTION:
How can I solve this problem? How to remove the file which has opened handles? May be exists something like "force deletion"?

推荐答案

p>问题是,你不是唯一的处理你的文件。其他进程和服务也能够打开该文件。所以删除它是不可能的,直到他们释放他们的句柄。您可以在打开这些句柄时重命名文件。您可以在打开这些句柄时复制文件。但是,不确定是否可以将文件移动到另一个容器中?

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.

这是我在Windows下完成立即删除的函数:

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;
}

这篇关于如何删除已打开句柄的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆