Here I am explaining one common scenario, I faced......
There can be situations in which you are needed to delete files which are locked by other processes. This can be because the process still holds some handles or references corresponding to this code files.
You can use unlocker to check what are processes which hold lock on these files.
There is 2 ways you can make the file deletable:
1. Find the list of processes which holds the lock and kill the process => but it is not desirable.
2. You can use windows APIs like MoveFileEx to mark the files as deletable on system reboots. Here system will add a registry entry for the files and will be deleted on next system reboot.
Behind this API, it just adds a value to record the pending deleted files under the registry entry “[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\PendingFileRenameOperations]”. Windows will detect this registry entry after reboot and delete all recorded files.
Below is the sample code :
once you execute the above code, you can check your registry entry which will be updated as below:
There can be situations in which you are needed to delete files which are locked by other processes. This can be because the process still holds some handles or references corresponding to this code files.
You can use unlocker to check what are processes which hold lock on these files.
There is 2 ways you can make the file deletable:
1. Find the list of processes which holds the lock and kill the process => but it is not desirable.
2. You can use windows APIs like MoveFileEx to mark the files as deletable on system reboots. Here system will add a registry entry for the files and will be deleted on next system reboot.
Behind this API, it just adds a value to record the pending deleted files under the registry entry “[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\PendingFileRenameOperations]”. Windows will detect this registry entry after reboot and delete all recorded files.
Below is the sample code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace LockedFileDeletion
{
class Program
{
[Flags]
enum MoveFileFlags
{
MOVEFILE_REPLACE_EXISTING = 0x00000001,
MOVEFILE_COPY_ALLOWED = 0x00000002,
MOVEFILE_DELAY_UNTIL_REBOOT = 0x00000004,
MOVEFILE_WRITE_THROUGH = 0x00000008,
MOVEFILE_CREATE_HARDLINK = 0x00000010,
MOVEFILE_FAIL_IF_NOT_TRACKABLE = 0x00000020
}
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
static extern bool MoveFileEx(string lpExistingFileName, string lpNewFileName, MoveFileFlags dwFlags);
static void Main(string[] args)
{
string fileName = @"c:\LockedFile.txt";
MoveFileEx(fileName, null, MoveFileFlags.MOVEFILE_DELAY_UNTIL_REBOOT);
}
} }once you execute the above code, you can check your registry entry which will be updated as below:
No comments:
Post a Comment