- Delete on close windows
- CreateFile with the FILE_FLAG_DELETE_ON_CLOSE flag
- Delete on close files
- 3 Answers 3
- FILE_FLAG_DELETE_ON_CLOSE and memory mapped files
- 2 Answers 2
- www.makeuseof.com
- Follow MUO
- How to Delete a File in Use by Another Program
- How to Overcome the «File in Use» Error
- 1. Close the Program
- 2. Reboot your computer
- 3. End the Application via the Task Manager
- 4. Change File Explorer Process Settings
- 5. Disable the File Explorer Preview Pane
- 6. Force Delete the File in Use via the Command Prompt
- Unlock the File in Use With a Tool
- 1. Microsoft Process Explorer
- 2. Unlocker
- 3. LockHunter
- File Still in Use? Boot Into Safe Mode
- More Windows File Explorer Tricks to Know About
- Subscribe To Our Newsletter
- One More Step…!
Delete on close windows
Хочу реализовать метод удаления временных файлов после использования. Для этого думал воспользоваться FILE_FLAG_DELETE_ON_CLOSE при CreateFile, на XP работает отлично — но вот на Windows 7 не работает. Мне нужно запустить один dummy.exe и удалить его после завершения процесса (либо моего процесса, либо dummy.exe). Так вот проблема в том что после того как я скопировал файл в Temp директорию пытаюсь его открыть с флагом FILE_FLAG_DELETE_ON_CLOSE, но после этого не работает CreateProcess — либо наоборот, запускаю файл (CreateProcess) и после пытаюсь открыть файл — нет доступа. Как быть?
| От: | IID |
Дата: | 13.10.09 18:48 | |
Оценка: |
Здравствуйте, xrc2, Вы писали:
X>Привет.
X>Хочу реализовать метод удаления временных файлов после использования. Для этого думал воспользоваться FILE_FLAG_DELETE_ON_CLOSE при CreateFile, на XP работает отлично — но вот на Windows 7 не работает. Мне нужно запустить один dummy.exe и удалить его после завершения процесса (либо моего процесса, либо dummy.exe). Так вот проблема в том что после того как я скопировал файл в Temp директорию пытаюсь его открыть с флагом FILE_FLAG_DELETE_ON_CLOSE, но после этого не работает CreateProcess — либо наоборот, запускаю файл (CreateProcess) и после пытаюсь открыть файл — нет доступа. Как быть?
| От: | xrc2 |
Дата: | 14.10.09 07:03 | |
Оценка: |
Надо юзать поиск!
Дык, а толку? Все равно ведь решение не найдено, акромя конечно же watcher.bat файла. Да и еще учитывая тот факт что решение то не полностью работает на Windows Vista а у меня проблема с Windows 7.
| От: | xrc2 |
Дата: | 14.10.09 07:47 | |
Оценка: |
Здравствуйте, xrc2, Вы писали:
X>Привет.
X>Хочу реализовать метод удаления временных файлов после использования. Для этого думал воспользоваться FILE_FLAG_DELETE_ON_CLOSE при CreateFile, на XP работает отлично — но вот на Windows 7 не работает. Мне нужно запустить один dummy.exe и удалить его после завершения процесса (либо моего процесса, либо dummy.exe). Так вот проблема в том что после того как я скопировал файл в Temp директорию пытаюсь его открыть с флагом FILE_FLAG_DELETE_ON_CLOSE, но после этого не работает CreateProcess — либо наоборот, запускаю файл (CreateProcess) и после пытаюсь открыть файл — нет доступа. Как быть?
В общем отвечаю сам себе.
Выделил для себя несколько методов самоудаления.
1) .bat файл.
2) Inject в чужой процесс пусть это будет explorer.exe и от туда в лупе удаляем все что нам нужно. (сложен в реализации)
3) Очень понравился один метод через NTFS Stream. подробнее здесь. Проблема в том что будет работать только с NTFS, но к этому методу думаю можно прикрутить способ с FILE_FLAG_DELETE_ON_CLOSE для FAT’а — и думаю получиться универсальное решение, ну и конечно же можно для точной уверенности добавить 1) метод.
Кто что думает по поводу 3) метода?
| От: | IID |
Дата: | 15.10.09 07:51 | |
Оценка: |
Здравствуйте, xrc2, Вы писали:
X>Выделил для себя несколько методов самоудаления.
X>1) .bat файл.
Пойдёт. Плюс MoveFileEx + DELAY_UNTIL_REBOOT
X>2) Inject в чужой процесс пусть это будет explorer.exe и от туда в лупе удаляем все что нам нужно. (сложен в реализации)
Отвратительный метод. Сваливать свое говно в чужие процессы. Очень «улучшает» стабильность работы.
К тому же запросто может не быть прав на открытие других процессов. Плюс антивирусы/ХИПСы поднимут вой на такое безобразие (и правильно).
X>3) Очень понравился один метод через NTFS Stream. подробнее здесь. Проблема в том что будет работать только с NTFS, но к этому методу думаю можно прикрутить способ с FILE_FLAG_DELETE_ON_CLOSE для FAT’а — и думаю получиться универсальное решение, ну и конечно же можно для точной уверенности добавить 1) метод.
Стримы — излюбленное место вирусов. (Например Rustock). Антивирусы давно про это в курсе. Если будешь писать в стрим PE файл нарвёшься на вой антивирусов и ХИПСов.
Тебе для чего это нужно ? Uninstall ? Юзай MSI пакеты и не изобретай велосипед.
CreateFile with the FILE_FLAG_DELETE_ON_CLOSE flag
Before I describe my problem, here is a description of the program (IHExplorer.exe) I’m writting:
This is a C++ application.
The IHExplorer application is to look as much like a Windows Explorer window as possible. With one exception, and that is that launching files from within this Explorer window will decrypt them first to the user’s temp folder, then launch the app associated with the file extension and delete the file on close.
The problem i’m having is with the auto delete when the file is closed. Here’s a scenario:
- User double clicks an encrypted .txt file in IHExplorer.
IHExplorer decrypts the .txt file in memory, then writes it to %TEMP% using ::CreateFile which returns a HANDLE to the file (IHExplorer has to keep this handle open atleast until the .txt file is shell executed).
IHExplorer Shell Executes the .txt file (by calling ::ShellExecute) from it’s temp location.
ok. that is a basical User Case that describes what I want to happen. The problem I have is when I ::ShellExecute(), notepad says «The process cannot access the file because it is being used by another process.» (which would be IHExplorer). I need to get around this and have notepad open it even while I still have the handle open in IHExplorer.
Here’s what my call to ::CreateFile looks like:
Notice I used FILE_SHARE_DELETE so that other processes (such as notepad) can open the file with delete access.
Notice that I used the FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE attributes to indicicate the the file is temporary and should be deleted on close.
Also notice the &sa parameter. This is the SECURITY_ATTRIBUTES structure that I am using, and I feel (hope) this is where my problem lies. Here is the code again, this time I will post the entire function so you can see how I fill out the SECURITY_ATTRIBUTES structure:
I think if I determine the correct SECURITY_DESCRIPTOR to pass to ::CreateFile it may work like I want it to. Please help.
btw, the LaunchFile function just ends up calling ::ShellExecute to launch the file.
Delete on close files
Language used: C#
Theory: I want to create a file with the flag FileOptions.DeleteOnClose in a temporary folder. The file is successfully created and I write dato onto it, the next step is to launch the application associated with the file Process.Start(. ) and allow the user to inspect the document, finally I close my handle and as soon as other process close the handle to the temporary file, the file is deleted by operating system.
My problem is that other processes cannot open the file, even for reading, despite if I add FileShare.ReadWrite | FileShare.Delete to the sharing mode.
3 Answers 3
The other processes need to specify FileShare.Delete when they open the DeleteOnClose file
» FILE_FLAG_DELETE_ON_CLOSE . Subsequent open requests for the file fail, unless the FILE_SHARE_DELETE share mode is specified.»
You need to make sure that all processes are opening the file with FileShare.ReadWrite and FileShare.Delete.
Even if the creator opens with share-readwrite, if a second program tries to open with share-read, the second program is basically saying no-one else can write. But the first program already has that power so the second open fails.
Switch to Linux scnr
Ok, seriously now: That is a flaw in the Windows operating system which can’t really be worked around. Each program opening the file must agree on other programs having the file open in the same time. That was a problem I got many years back when I still used Windows as well. It doesn’t suffice to open a file and say: Let anyone else open this as well. The others must also say open this file even if it’s open already.
On Linux on the contrary, the operating system doesn’t allow any file locking in the way Windows does at all. Here, if any file is used by more than one program simultaneously, the programs itself must make sure, that concurrent accesses get locked out. Additionally, on Linux, we can just create the file, make sure the other process has been started and opened the file and then just delete the file (while it is open). The filename is then removed from the file system immediatelly, but the file is still maintained by the file system driver until the last link (including open file handles) got removed.
Back to your problem: As all of this doen’t work on Windows, you could do two other approaches:
FILE_FLAG_DELETE_ON_CLOSE and memory mapped files
Not that it’s particularly useful, but I’m curious as to why the following works, is it simply because the page still happens to be in memory even after the file is deleted? In which case, if the page is swapped out the data will be lost?
2 Answers 2
FILE_FLAG_DELETE_ON_CLOSE follows the unfortunate Windows tradition of referring to an unlink operation as «delete». In fact, the flag only causes the file to be unlinked from the specified directory when the file is closed.
Like other operating systems, Windows only gives ordinary user code the ability to unlink a file from a particular directory. Deleting is always the operating system’s decision, taking place when the file can no longer be referenced in any way.
If you look, you’ll see the file has in fact been unlinked from the directory, but it will not actually be deleted (and the space the data takes on disk available for re-use) until its reference count drops to zero. The mapping holds a reference.
Windows is different from Linux and other Unix-alikes in this regard. It maintains a separate reference and handle count for each FILE_OBJECT . When the last handle is closed, the filesystem unlinks the file and switches it to a «deleted» state. Meanwhile the FILE_OBJECT might live longer in a «deleted» state until reference count drops to zero.
The file gets deleted when you close the file handle. After this, if any pages from the view are trimmed and repurposed and then accessed again, the memory manager will try to read them from the file (which is now in the «deleted» state). What happens next depends on the filesystem. NTFS returns an error code ( STATUS_END_OF_FILE ) which causes the memory manager to satisfy the page fault with zeroed pages. As far as I can tell, this behavior is not documented so a future version of NTFS (or a different filesystem) could return a different error, which would result in an inpage exception instead.
That means that once the file is unlinked, swapped-out data will be lost and replaced with zeroes.
You can observe this behavior with the program below. It does the following:
- Creates a file of a size equal to the amount of RAM with FILE_FLAG_DELETE_ON_CLOSE .
- Maps it into memory.
- Deletes the file by closing the last handle to it.
- Fills file content with 0xCD pattern. Since the file is as large as RAM, this should force pages out of a memory and into a file.
- Prints first 16 bytes of the mapping.
The output says the data at the beginning of the mapping is all zeroes — data has been lost. It is not clear if this can be considered a bug, but as of today this behavior is at least 12 years old and is not likely to be changed.
www.makeuseof.com
Follow MUO
How to Delete a File in Use by Another Program
Windows says your file is in use because it’s open in another program? We show you how to force rename, delete, or move the file.
Windows File Explorer claims the file you’re trying to delete is open in another program or the system? When you can’t open, edit, or delete a file, it’s either still running in the background or didn’t close properly.
Fortunately, you can force close, rename, move, or delete a file that is in use. Here’s how!
How to Overcome the «File in Use» Error
If you want to skip the manual solutions, scroll down to the section where we list tools that can help you unlock and delete a file in use.
1. Close the Program
Let’s start with the obvious. Did you just open the file and not close it? If the file is closed, but the program is still running, close it too, then try again.
2. Reboot your computer
While rebooting is inconvenient, it requires zero skills or fiddling with stuff like the Task Manager or third party tools. Rebooting also clears your RAM and possibly fixes other nuisances in one go. So try this if you can’t be bothered to look into the cause.
If you have already tried rebooting and it didn’t help, skip to the next option.
3. End the Application via the Task Manager
The reason rebooting helps is because the system will start from scratch and—among other things—all processes currently running in the Task Manager will be closed. Instead of rebooting, you can also try to manually end the process or application that holds your file hostage. This is the most successful method to fix the «file is open in another program» error.
Click Ctrl + Shift + ESC to open the Task Manager. Alternatively, you can right-click the Taskbar or click Ctrl + Alt + Del anywhere in Windows and select Task Manager. If you see the compact Windows 1o version, click More details and make sure you’re in the Processes tab. Now browse for the application that you used to open the «file in use». For example, if you were viewing a document, look for Word.
Once you find the process, select it and click End task in the bottom right. This will close all instances of the program. If you cannot seem to find the process, have you tried rebooting, yet?
4. Change File Explorer Process Settings
By default, File Explorer launches all its windows in a single process (explorer.exe). It could be, however, that your settings force File Explorer to launch separate processes, which could cause a conflict between different processes.
Press Windows + E to open File Explorer. Go to View > Options > Change folder and search options.
In the Folder Options window, switch to the View tab and find the Launch folder windows in a separate process option. Make sure it’s not checked. Click Apply to save any changes.
If the option was unchecked in the first place, you could try if checking it solves your issue.
5. Disable the File Explorer Preview Pane
Previews in the File Explorer can cause conflicts like the «file is open in another program» error.
Press Windows + E, switch to the View tab, and press Alt + P to close the preview pane. The screenshot below shows an open preview pane on the right.
After closing the preview pane, try the operation again and see whether the «file in use» error has disappeared.
6. Force Delete the File in Use via the Command Prompt
You can bypass the File Explorer and force delete the file using the command prompt.
First, we need to track down the file path directory in File Explorer. Press Windows + E to open file explorer, locate the affected file, and copy the file path.
Now press Windows + S, search for Command Prompt, right-click the respective result, and select Run as administrator. To navigate to the file directory of your file in use, enter cd [directory path you copied] and hit Enter.
Before we can proceed and force delete the file in use, we have to temporarily kill the File Explorer process. This will cause your Taskbar, wallpaper, and open folders to disappear. But don’t worry, you can restart File Explorer and we’ll show you how below.
To close File Explorer, press Ctrl + Shift + ESC, find Windows Explorer, right-click the process, and select End task.
Return to the Command Prompt. If you lost the window, press Alt + Tab to jump to it.
Enter this command to delete the file, replacing everything between the quotes with your actual file name:
To restart the File Manager, open the Task Manager (Ctrl + Shift + ESC), click File > Run new task, enter explorer.exe, and click OK. This should restore your desktop to its usual appearance.
Unlock the File in Use With a Tool
Sometimes, the file in use remains locked, even though it shouldn’t be. If trying to delete it through the Command Prompt didn’t work or if that task is too daunting, use one of these tools.
1. Microsoft Process Explorer
Process Explorer is a more powerful File Explorer. It doesn’t just list all running processes, it can also show you which process took your file hostage. Simply open the Process Explorer Search via Find > Find Handle or DLL (or press Ctrl + F), enter the file name, and wait for the list of processes accessing your file.
You can’t close the process from the search window, but you can use Process Explorer or Windows Task Manager to close the offending application.
2. Unlocker
Unlocker used to add itself to the Windows context menu, meaning you could right-click the file in use and unlock it via the context menu.
In Windows 10, launch Unlocker, browse for the file, select the file, and click OK. Unlocker will look and (if found) remove locking handles. Even if it does not find a handle, you can use Unlocker to Delete, Rename, or Move the file.
Should the file still be in use, you can let Unlocker perform the action upon your next reboot.
3. LockHunter
LockHunter will add itself to the Windows context menu. Once installed, just right-click the locked file and select What is locking this file? This should bring up a window showing all processes using the file. You can now select to Unlock, Delete (at next system restart), or Unlock & Rename the file. In our case, we couldn’t unlock the file, but deleting it at the next system restart did work.
Another third-party tool, FilExile, failed to delete our file in use, even though it reported success. However, if your file path is too long, you might still want to give this tool a try.
File Still in Use? Boot Into Safe Mode
If the above didn’t work or if you’re not interested in installing software, there is one last thing you can try: boot into Windows Safe Mode. The file you’re trying to delete may automatically be loaded by another application. Unlockers should still work if that’s the case, but if malware is involved or if you don’t want to deal with third-party tools, this is an alternative route you can take.
In Windows 10, press Windows + I, navigate to Update & Security > Recovery and under Advanced startup select Restart now. From the next screen, select Troubleshoot > Advanced Options > Startup Settings > Restart. When your computer reboots, you’ll see the Startup Settings screen, from where you can choose Safe Mode.
Once you’re in Safe Mode, navigate to the file in question and try your luck once more.
More Windows File Explorer Tricks to Know About
We showed you a few ways to unlock a file open in another program or in use by the system. Hopefully, one of them worked. Two methods involved the Windows File Explorer.
To make your videos advertiser-friendly, you need to abide by a set of guidelines. Here’s everything you need to know.
While completing a PhD, Tina started writing about consumer technology in 2006 and never stopped. Now also an editor and SEO, you can find her on Twitter or hiking a nearby trail.
Subscribe To Our Newsletter
Join our newsletter for tech tips, reviews, free ebooks, and exclusive deals!
One More Step…!
Please confirm your email address in the email we just sent you.