Deleting Locked Files

Environment: Windows NT4 SP6, Windows 2000

This is a command line utility to close and delete a file which is locked by another process. I doesn't work with modules.

Usage

FORCEDEL.EXE [/S] filename

/S             Soft delete. Like the "del" command
filename       File name you want to delete

How does it work?

  1. Query the used file handles (system wide), and search for the processes which are using the file we want to delete.
  2. For more information, check out the CodeGuru article entitled, Examine Information on Windows NT System Level Primitives.

  3. Start a remote thread (CreateRemoteThread) to close the given handle in every found process (#1)

Code

The following code closes a handle in a remote process. The handle must be remote process specific.
/*
Note: 1. SE_DEBUG privilege must be enabled. 
      2. The function works with every kind of HANDLE
      3. It will bother the remote process :)
      4. The handles will be invalid after you closed 
         them remotely
*/

//Close a handle in a remote process
DWORD CloseRemoteHandle( DWORD processID, HANDLE handle )
{
 HANDLE ht = 0;
 DWORD rc = 0;
	
 _tprintf( _T("Closing handle in process #%d ... "), 
          processID );

 // open the process
 HANDLE hProcess = OpenProcess( PROCESS_CREATE_THREAD 
                                | PROCESS_VM_OPERATION 
                                | PROCESS_VM_WRITE 
                                | PROCESS_VM_READ, 
                                FALSE, processID );
	
 if ( hProcess == NULL )
 {
  rc = GetLastError();
  _tprintf( _T("OpenProcess() failed\n") );
  return rc;
 }

 // load kernel32.dll
 HMODULE hKernel32 = LoadLibrary( _T("kernel32.dll") );

 // CreateRemoteThread()
 ht = CreateRemoteThread( 
  hProcess, 
  0, 
  0, 
  (DWORD(__stdcall *)(void*))GetProcAddress(hKernel32,"CloseHandle"),
  handle, 
  0, 
  &rc );
	
 if ( ht == NULL )
 {
  //Something is wrong with the privileges, 
  //or the process doesn't like us
  rc = GetLastError();
  _tprintf( _T("CreateRemoteThread() failed\n") );
  goto cleanup;
 }

 switch ( WaitForSingleObject( ht, 2000 ) )
 {
  case WAIT_OBJECT_0:
   //Well done
   rc = 0;
   _tprintf( _T("Ok\n"), rc );
  break;
	
  default:
   //Oooops, shouldn't be here
   rc = GetLastError();
   _tprintf( _T("WaitForSingleObject() failed\n") );
   goto cleanup;
  break;
 }

 cleanup:
 //Closes the remote thread handle
 CloseHandle( ht );

 //Free up the kernel32.dll
 if ( hKernel32 != NULL)
  FreeLibrary( hKernel32 );

 //Close the process handle
 CloseHandle( hProcess );
	
 return rc;
}


Downloads

Comments

  • Chi lisseur vous donne une coiffure différente chaque jour

    Posted by pmbqwm754 on 07/16/2013 04:35pm

    Source GHD d'inspiration provient de toutes les directions, et lance bague av la nouvelle édition limitée GHD, GHD et symbole de luxe, kombinert avec un paon chaud et beau, paon inspirert Utforme un charismatique Peacock GHD rettetang.Hot Vente GHD Purple Limited Edition Peacock, au nom organisme officiel av , profondeur prestisje et spirituelle. Le paon pourpre droit tige Bruke rik émeraude pourpre, paon Chaque tige droite ghd a tout funksjonene l'articulation, un ghd Gold Classic Styler avec fargede plaqueur et aksenter, et une plaque de protection suscité, avec un oppbevaringspose luxe et rull terne. [url=http://ghdpascherfer.tripod.com/]ghd pas cher lisseur[/url] Maintenant, avec tension universelle pour une performance optimale partout dans le monde que vous êtes deg.Hvilemodus est une configuration de sécurité intégré qui vous donne la tranquillité d'esprit, car il s'éteint automatiquement technologie numérique av.Unik signifie que la température est contrôlée automatiquement encore plus rapide pour un meilleur style. New rounder baril de sorte qu'il est facile de créer des boucles parfaites, vagues ou chiquenaudes, ainsi que les supprimer. [url=http://ghdpascherfer.tripod.com/]ghd pas cher lisseur[/url] Faites le jour de Noël et tous les jours pendant une bonne journée de cheveux avec l'édition limitée ghd Metallic Collection cadeau set.Inspired de l'esprit de Noël, look métallique collection ghd styler ghd classique V donné un glamour make-over avec une belle nouvelle Rich Ruby ombre rouge et éclat métallique éblouissante finish.Created avec sleekest ghd à ce jour, la collection Metallic ghd étincelante plaques profilées noires glisser sans effort dans les cheveux - en laissant votre style lisse et brillant si vous choisissez lisse et les cheveux raides, les vagues sexy ou boucles gros et plein d'entrain, exactement ce que vous attendez avec la qualité superbe de certains lisseur ghd stylers et.

    Reply
  • By using lusus naturae beats is crap-shooter than others headphones

    Posted by motherdhmm on 06/04/2013 05:05pm

    [url=http://www.headphonescheaponlineaustralia.com/]beats headphones Australia[/url] Beats by Dr. Dre pro created a transportable top-class title is called Beats by Dr. Dre. These headphones are made with high-end speakers and headphones of Frightfulness Cable Products Dre. adopted covered by the astronomical good fortune in the market, Dr. Dre, a comprehensive assortment of products to the most useful in requital for musicians. Now, the premium latitude of versatile phones is bleeding distinct faculty great quality are at in different shapes and colors in the collection of Beats by means of Dr. Dre headphones. They are equipped with speakers and high- definition, digital hubbub reduction technology. [url=http://www.headphonescheaponlineaustralia.com/]dr dre beats[/url] Miscreation headphones of Kobe Bryant, he is way down engraved on the reminiscence of basketball lovers. Beats on Dre make broad demand of this principal essentially to invent a restrictive number headphone named Beats at hand Dr. Dre Studio Kobe Bryant Meagre Printing Headphones. There is no doubt that this headphone will be the with greatest satisfaction seller at present. You can not brush off the high-quality of this and the in perfect accord mould which prompt our mind. Monstrosity headphones with rumour canceling technology are on the engraving brim of lean that spreads nationwide. [url=http://www.headphonescheaponlineaustralia.com/]beats by dre Australia[/url] The right with reference to Dragon Beats Individual headphones: The Beats On one's own by Dr. Dre Headphones from Monster proffer a stylish, small, and sturdy design that lends itself nicely to on-the-go use.The mooring is ultranice and features an integrated mic, iPod controls, and sum total rocker.Bass is thumping, and the bundle includes a clever carrying case. because of its small size, indulgent to convey, so the unseasoned materials needed in the in britain artistry prepare more in the bazaar prices were comparatively cheap, cheaper then Beats nearby Dr. Dre Studio Diamond Headphone the Red in Australia, as long as you keep 150USD that, you can not the get it from the Beats beside Dr. Dre online.

    Reply
  • Beats by Dre sportslige stilfuldt – men ikke sponsor-brand – hovedtelefoner pÃ¥ spil

    Posted by wanzixiao on 06/04/2013 08:22am

    [url=http://www.beatsbydrdredanmark.blinkweb.com/]beats by dre danmark[/url] Hestekræfter samt reggae hele verden har kombineret såvel som resultatet er den nye Doctor Dre laptop. Med ferier her og også Dr. Dre laptop annoncer viser konstant på tv, er alle spekulerer på, om de skal købe det faktiske H. s.. Misundelse (den bestemte specialiserede navn med den personlige computer).Over-the-ear hovedtelefoner er fantastisk for ejendom bliver opmærksomme samt vejledning i at lukke ud lyde som du sover. On-ear typer bør også være behageligt, sammen med delikat ekstra polstring og robust konstruktion. Bare om de mest væsentlige ting sammen med on-ear design er at sikre, at de er installeret til brug sammen med stikkene i dine gadgets. [url=http://www.beatsbydrdredanmark.webgarden.com/]Beats by dre billig pris[/url] Hvis man ville præcisere, hvad præcist udrette audio transskription tjenesteudbydere samt transskribere tjenester udføre, svaret er, som de fuldføre opgaven med at konvertere musik information i elektronisk fil info. Hvis det overhovedet er muligt, kan en uddannet transcriptionist lytte til lyd tape løsninger, der har brug for at konvertere, og derefter dokumentere dem i en elektronisk digital fil, der kan helt sikkert være en sætning fil eller tilknyttede fil formatering. [url=http://www.beatsbydrdredanmark.blinkweb.com/]beats by dre danmark[/url] monster beats hovedtelefoner tendens til at være på det aspekt af en fremragende synes høj kvalitet og vidunderlige overordnede udseende. Efter min mening, hvis du ofte har en god fan vedrørende lyd til eller gå med sange af en stringent tilgang, eller du bare brug for at få din arbejdsplads med fremragende afslapning, så er du måske nødt din bil beruset med sin perfekte lydkvalitet fremragende.

    Reply
  • You Can Áridas GHD Niza Straignteners Cabello

    Posted by hanmeihm on 05/30/2013 07:00pm

    [url=http://www.planchasespanaghdtop.net/ghdtienda/]GHD Plancha pelo[/url] GHD tiene una norma que eclipsa a cualquier otro fabricante en el mercado hoy en da. Estos alisadores son tan populares, muchos vendedores tratan de duplicar. Es por esta razn usted debe estar seguro que usted est comprando de un vendedor autorizado. [url=http://www.ghdplanchasonline.manifo.com/]planchas ghd baratas[/url] Si estoy siendo absolutamente brutalmente honesto, no puedo reall decir la diferencia con el pelo de los ltimos alisadores que usaba. Pero de todos modos, ella me asegura que son mucho m¢s f¢ciles de usar, mejores placas de cer¢mica (aparentemente), mejor manejo, etc As que los buenos tiempos. En caso de duda, apoderarse de un conjunto de GHDs y te golpeaste la fiesta anual de la tensin de cumpleaos. [url=http://www.planchasghdbaratasonline.com/ghd-styler/]ghd Styler[/url] Imagina que estoy tentado a ofrecerme, pero el precio de € 245 puede ser un poco de freno a comprar ... Al mismo tiempo, la innovacin tecnolgica puede ser interesante si suavizar el cabello regularmente. Respeta el cabello se calienta en 20 segundo y tiene un control total de la temperaturaS, se vende un poco de sue?o, pero queremos creer, al menos yo (creo).

    Reply
  • GHD MK4 sort

    Posted by motherdhmm on 05/30/2013 05:06pm

    [url=http://www.blog.cheapbeatsbydre.co.nz/beats-by-dre-headphones]beats by dre headphones[/url] En ideel kvinde er ofte afbilledet til at være en person med en slank figur med langt hår. Hår har altid været vigtigt for hver kvinde, fordi det en eller anden måde afspejler deres personlighed. Have lange skinnende hår kan forføre en mand, kan det lander en kvinde i en shampoo kommercielle, eller få komplimenter fra andre. Det kan afspejle en kvindes sundhed og giver et indtryk af, at hun er sund, og at hun tager sig godt af sig selv. Selvfølgelig ville det ikke alle kvinder vil have langt hår. [url=http://www.buy-beatsdrdre.com/category/monster-beats-australia]monster beats australia[/url] Den faktiske given mængde inde i mængden middage indeholder 4. 5 inches lang med henblik på dels. 5 ins tykkelse og også du kan vælge afhængig af god låse rækkevidde, beregnet til alle, der er en specialist og endnu nybegynder og meget mere. i situation, du har fået korte Lokker, kan din specifikke to, fem inches massiv skål være nok. En stor del langt mere sammen med større manke, kan det især øget væsentlig en aftenmåltid kan anbefales [url=http://www.blog.cheapbeatsbydre.co.nz/monster-headphone]monster beats headphone[/url] Hurtigt snart efter detoksificering låse, følgende gør nogen forskel i øjeblikket at blive i stand til at eventuelt kunne være blevet tabt hår. De er rent faktisk nødvendigt at undgå vilde hår skade som følge af varme niveau priser pres på grund af type og konstruktion regnfulde og desuden fugtigt krøllede hår. Umiddelbart efter erhvervelse af for at blive udtørret låse, skal du helt oprydning denne bestemte slags, så du kan fjerne troubles sammen med hår. Sørg som head of hår kan være helt helt moderne sammenholdt med gået tabt ved udnytter plus desuden drage fordel med de sande ghd fladjern tekniske personale, overbevisninger protectant. At kunne erhverve til at blive en specifik forsvarende flick, så du kan reducere varme niveau værdier skade bil Frisure plus stil tilgang. Varm temperatur protectant kan også dygtig bo klart af tilfældige krøllede hår anvender op.

    Reply
  • Isabel Marant Sneakers

    Posted by Hauddessy on 03/28/2013 03:19pm

    [url=http://future-select.co.uk/fckeditor/isabelmarantsneakers.aspx]sneaker isabel marant[/url] 07 qiu dong demonstrate,,, like mashups, low-key, can relevance! Isabel Marant is new era designers in France, a occasional won a fellow of the international manufacture humankind attention. After graduating from invent school in Paris Studio Bercot, Isabel Marant Yorke and Cole in his figure as a underling a ally with to follow. Spring/summer 2008 the rage confirm in Paris - the Isabel Marant [Isabel Marant is ardent! Morning star facsimile clothing increased in sneakers tide zealot into public notice street "mixing in the" unavoidable Just look at personage lane snap, well-founded know, Isabel Marant sneakers increased progress in Europe and the Mutual States is a official vim! Vip, famous model wearing! By fashion make Isabel ma LAN (Isabel Marant) to drive the motion of the new cyclone, with great skirts, pants, leather pants, etc. Different particular with Isabel ma LAN (Isabel Marant), fashion sneaker row perk up demonstrations, deal sports sandals feeble rocks in inspiration. Isabel ma LAN (Isabel Marant) shoot once pushed on this kind of shoes is in shape widely, snapping up, at proximate in diverse peculiar shopping website have been sold out. Miranda Kerr, negroid leather pants with red [url=http://gateway.recruitment-websites.co.uk/fckeditor/isabelmarant.aspx]isabel marant heels[/url], sufficiency of the color and style. Sulky and silver match colors, Isabel Marant tie-in and constricting jeans, locomotive leather, big Blacklist and undefiled contest colors Isabel Marant jeans copy and the whole heart Isabel Marant Black unite dress + frog picture, is not a low profile Kate potts voss, Isabel Marant sneaker together with the heap amateur chiffon dresses to wear, de-emphasize delay is a mashup Solid cream + hand-knitted sweater fastens with color Isabel Marant Isabel Marant sneaker,Cambridge carton fluorescent color highlight is the aggregate body Lovers outdoors of the street, Isabel Marant makes sense at wish Isabel Marant Website is efforts to donation a diminish now. Isabel Marant shoes Lovely mature color Isabel Marant sneaker Lightning blue and pink are quite forgive a ourselves enchanted. The multicolor deployment plus ultra

    Reply
  • File not found ?

    Posted by james on 06/27/2012 01:25am

    hallo, if I want to build the downloaded project there is missed the "SystemInfo.h"-file. Is this a class built by you or is this a WIN-SDK-File ? best regards james

    Reply
  • delete file

    Posted by KenRayn on 02/13/2012 06:35pm

    well you can use a program for this like LongPathTool.com maybe ? :)

    Reply
  • Missing Files

    Posted by pislas on 09/11/2008 03:33pm

    Some of the files are missing from this download...cant make it compile, and it doesnt delete my in use files when i run it on them... ForceDel.exe "testfile.txt" SystemProcessInformation::Refresh() failed. Couldn't delete. Error = 32

    Reply
  • Couldn't delete. Error = 5

    Posted by glenneroo on 02/18/2007 02:15am

    SystemProcessInformation::Refresh() failed. Couldn't delete. Error = 5 when deleting this odd file that's from my old windows. It's the only file left before i can reformat this drive, but Vista won't let me :( D:\WINDOWS\system32\Macromed\Flash\Flash9.ocx any ideas?

    Reply
  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • On-demand Event Event Date: September 10, 2014 Modern mobile applications connect systems-of-engagement (mobile apps) with systems-of-record (traditional IT) to deliver new and innovative business value. But the lifecycle for development of mobile apps is also new and different. Emerging trends in mobile development call for faster delivery of incremental features, coupled with feedback from the users of the app "in the wild." This loop of continuous delivery and continuous feedback is how the best mobile …

  • Java developers know that testing code changes can be a huge pain, and waiting for an application to redeploy after a code fix can take an eternity. Wouldn't it be great if you could see your code changes immediately, fine-tune, debug, explore and deploy code without waiting for ages? In this white paper, find out how that's possible with a Java plugin that drastically changes the way you develop, test and run Java applications. Discover the advantages of this plugin, and the changes you can expect to see …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds