How to delete a locked file in C# program in next reboot? some times you may want to delete a file that is locked by other process this scenario may arise in situation such as un installation procedures, clean up operation or deleting a virus infected file in this type of scenarios you can use delete a file by scheduling it to delete in next bootup using MoveFileEx though this is a unmanaged api you can use it by using dllimport and pinvoking in C# below is the sample code snippet on how to do it.
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
public static extern bool MoveFileEx(string
lpExistingFileName, string lpNewFileName, int dwFlags);
public const int MOVEFILE_DELAY_UNTIL_REBOOT = 0x4;
public static void DeleteOnStartup(string fname)
{
if (!MoveFileEx(fname, null,
MOVEFILE_DELAY_UNTIL_REBOOT))
System.Windows.Forms.MessageBox.Show("unable to process");
}
call the delete function from start or in any event trigger
static void Main(string[] args)
{
DeleteOnStartup(@"C:\lockedfile.txt");
}
though i did not get any direct api to do this in managed code C# if there is any do let us know
2 comments:
with:
using System;
using System.Runtime.InteropServices;
I know that it is an old post, but how can I do that for copying locked files?
Post a Comment