Deleting files that are under use...

This is a discussion on Deleting files that are under use... within the Windows Programming forums, part of the Platform Specific Boards category; Hi. I want to delete a file that is under use but I don't know how... so Maybe you could ...

  1. #1
    Banned Yuri's Avatar
    Join Date
    Aug 2005
    Location
    Breukelen, The Netherlands
    Posts
    133

    Deleting files that are under use...

    Hi.
    I want to delete a file that is under use but I don't know how... so Maybe you could help me. If I use Delete ( "path\\filename" ); I can delete normal files but this doesn't delete files that are being used.
    So I searched for it and I found this code but I don't understand it so I hoped you could help me. I really don't know how to use this code but I really want.

    I use Dev-C++ compiler and I have included windows.h.
    Here is the code:
    Code:
    bool newDeleteFile(LPCSTR lpFileName)
    {
    	OBJECT_ATTRIBUTES pObj;
    	UNICODE_STRING uFile;
    	WCHAR wFile[256];
    
    	// create an UNICODE path
    	swprintf(wFile, L"\\??\\%S", lpFileName);
    
    	// create UNICODE_STRING	
    	pRtlInitUnicodeString(&uFile, wFile);
    
    	// setup OBJECT_ATTRIBUTES for NtDeleteFile
    	InitializeObjectAttributes(&pObj, &uFile, OBJ_CASE_INSENSITIVE, NULL, NULL);
    	if(NT_SUCCESS(pNtDeleteFile(&pObj)))
    		return true;
    
    	return false;
    }
    If I try to use this code I get like 100 errors, here are some view:
    Code:
    `OBJECT_ATTRIBUTES' undeclared (first use this function)
     expected `;' before "pObj" 
    `UNICODE_STRING' undeclared (first use this function) 
    expected `;' before "uFile" 
    `uFile' undeclared (first use this function) 
     `pRtlInitUnicodeString' undeclared (first use this function) 
    `pObj' undeclared (first use this function) 
    `OBJ_CASE_INSENSITIVE' undeclared (first use this function)
    `InitializeObjectAttributes' undeclared (first use this function) 
    `pNtDeleteFile' undeclared (first use this function)
    `NT_SUCCESS' undeclared (first use this function)
    Thanks.

  2. #2
    Unregistered User
    Join Date
    Sep 2005
    Location
    Antarctica
    Posts
    341
    I may be wrong, but that looks like kernel mode code that would have to run in a driver (for instance NtDeleteFile)

  3. #3
    Registered User
    Join Date
    Mar 2005
    Location
    Mountaintop, Pa
    Posts
    1,059
    Yea, that's kernel mode stuff. You'll need the Windows NT Device Driver Kit (DDK) to compile/link that code. Currently, it'll cost you $199.00 for the DDK. But I'm not even sure that code snippet will do what you want it to do. That is, delete an executable that is currently be used.

    You may want to consider creating a child process and injecting your code into the child process. Then delete the parent process (executable) and let the child process exit. This is just theory and I'm not sure it will work. But it's a thought.

    Good luck

    Bob

  4. #4
    It's full of stars adrianxw's Avatar
    Join Date
    Aug 2001
    Posts
    4,831
    Deleting a file which is in use is not a particulaly valid thing to do. If it is in use, then something else is using it and removing it could have bad effects somewhere. That is why Windows prevents you from pulling the rug out from someone else.

    What EXACTLY is it you are trying to do?
    Wave upon wave of demented avengers march cheerfully out of obscurity unto the dream.

  5. #5
    Registered User
    Join Date
    Mar 2005
    Location
    Mountaintop, Pa
    Posts
    1,059
    I'm also curious as to what EXACTLY you're trying to do. In my previous post, I ASSUMED you were trying to write some sort of uninstaller where the uninstaller would delete itself at the very end of a uninstall. But anyway, I've attached a bare bones example of terminating an executable this is currently in use. You have to terminate the process of the executable and then delete the executable. The process id is found in the task manager. You can also use EnumerateProcesses to find the process id programmatically.
    Code:
    #pragma comment( lib, "advapi32.lib" )   // Search For advapi32.lib While Linking
    #include <windows.h>
    #include <stdio.h>
    // This will NOT terminate processess running under builtin\system AKA LocalSystem
    // Refer to SeDebugPrivilege on how to delete LocalSystem processes
    
    int main( int argc, char *argv[] )
    {
        int pid = 0;
        HANDLE hProcess;
    
        if(argc > 1 )
        {
            pid = atoi(argv[1]);
            if(hProcess = OpenProcess( PROCESS_TERMINATE, FALSE,  pid))
            {
                if (!TerminateProcess( hProcess, (DWORD) -1 ) )
                {
                    printf( "TerminateProcess() failed\n" );
                }   
                else
                {
                    printf( "Process %d terminated\n", pid );
                    // Delete the executable here
                }
                CloseHandle( hProcess );
            }
            else printf("OpenProcess failed\n");
        }
        else printf("Process ID NOT entered on command line\n");
        return 0;
    }
    Bob

  6. #6
    Banned Yuri's Avatar
    Join Date
    Aug 2005
    Location
    Breukelen, The Netherlands
    Posts
    133
    Sorry for reacting so late, I had some rough nights. I will explain everything as soon as possible. Thanks for your help.

  7. #7
    Banned Yuri's Avatar
    Join Date
    Aug 2005
    Location
    Breukelen, The Netherlands
    Posts
    133
    Explaination:
    You can create your one Unreal Bot with Unreal Engine 2 Runtime Demo and UMake then you can load it in the game, my Bot Loader.exe makes that easier. When the Bot is loaded it will delete it selfs. This wont affect the program cause the Bot only needs to be loaded, after being loaded you should be able to delete it without any affects to the program (the game) but if your bot doesn't has a "delete his self after loaded" function then it wont be deleted and when you try to delete it, it can't because it's "in use", that's why I am trying to create this "always delete" function, it wont affect the program (game).

    Now I got two questions:

    1. First I want to thank BobS0327 for his help but that's actualy my first question; Nice code but I really don't know how to use this, :S. Could you maybe explain the whole code and tell me where I need to add the string of the name and path of the file I want to delete? ( "path\\filename.***" ). Would you please help me with this, really really thanks!

    2. This is about something else; when you press Ctrl + Alt + Delete buttons then a window will pop up ( "Windows Control" ( or something like that ) ) you can see al the Processes there, is there also a way to check if a certain process is running in your program and if that process isn't running anymore then 'do that'?

    Thanks for any help, Yuri.
    Last edited by Yuri; 10-30-2005 at 06:25 AM.

  8. #8
    Registered User
    Join Date
    Mar 2005
    Location
    Mountaintop, Pa
    Posts
    1,059
    Yurie,

    There is a coment in the sample code -> // Delete the executable here. That is where you would put something like:

    Code:
     DeleteFile("C:\\TEMP\\MYFILE.TXT");
    Also, to find the process ID in task manager:

    1. Select the Processes tab

    2. If a PID column is NOT shown, go to View, Select Columns and make sure PID (Process Identifier) is checked

    3. Let's suppose Word is running. Find Winword.exe in the processes area. Under the PID column for Winword.exe is a number. That number is your pid number that you feed to OpenProcess in the sample code. As I said before, the pid can also be found programatically using EnumProcesses.

    Good Luck

    Bob

  9. #9
    Banned Yuri's Avatar
    Join Date
    Aug 2005
    Location
    Breukelen, The Netherlands
    Posts
    133
    Thanks for further information about your code, I finally seem to get it now but when I use it as a test it always sais: "Process ID NOT entered on command line" :S . I don't see what is wrong, here is the code I use: (I use Dev-C++ so I don't use #pragma but I link it in Project options, under tab Parameters: Compiler: -advapi32 C++ Compiler: Linker: -advapi32. )

    Code:
    #include <iostream>
    #include <windows.h>
    
    using namespace std;
    
    string Caption = "Test";
    
    int pid = 2336;//This is the correct PID.
    
    int main ( int argc, char * argv[] )
    {
        
        MessageBox ( 0, "Let's start", Caption.c_str(), MB_OK | MB_ICONWARNING );
        
        HANDLE hProcess;
    
        if ( argc > 1 )
        {
             
            pid = atoi ( argv[1] );
            
            if ( hProcess = OpenProcess ( PROCESS_TERMINATE, FALSE,  pid ) )
            {
                if ( ! TerminateProcess ( hProcess, ( DWORD ) - 1 ) )
                {
                     
                    MessageBox ( 0, "TerminateProcess() failed", Caption.c_str(), MB_OK | MB_ICONWARNING );
                }
                   
                else
                {
                    
                    MessageBox ( 0, "Process %d terminated", Caption.c_str(), MB_OK | MB_ICONWARNING );
                    
                    DeleteFile ( "C:\\Documents and Settings\\Admin\\Bureaublad\\Stomme test.exe" );
                }
                
                CloseHandle ( hProcess );
            }
            
            else
            {
                MessageBox ( 0, "OpenProcess failed", Caption.c_str(), MB_OK | MB_ICONWARNING );
            }
        }
        
        else
        {
            MessageBox ( 0, "Process ID NOT entered on command line", Caption.c_str(), MB_OK | MB_ICONWARNING );
        }
        
        return 0;
    }
    I really don't know why it always sais: "Process ID NOT entered on command line", I enterd PID correctly.

  10. #10
    Registered User
    Join Date
    Mar 2005
    Location
    Mountaintop, Pa
    Posts
    1,059
    Yuri,

    The original sample was a DOS console sample to be run from the command line. I have modified your code a little bit. All you have to do is compile/link it and run it. Just make sure 2336 is the correct process identifier.

    Bob
    Code:
    #include <iostream>
    #include <windows.h>
    
    using namespace std;
    
    string Caption = "Test";
    
    int main ( void )
    {
        HANDLE hProcess;
        int pid = 2336;//This is the correct PID.
    
        MessageBox ( 0, "Let's start", Caption.c_str(), MB_OK | MB_ICONWARNING );
        if ( hProcess = OpenProcess ( PROCESS_TERMINATE, FALSE,  pid ) )
        {
            if ( ! TerminateProcess ( hProcess, ( DWORD ) - 1 ) )
            {
                MessageBox ( 0, "TerminateProcess() failed", Caption.c_str(), MB_OK | MB_ICONWARNING );
            }
            else
            {
                MessageBox ( 0, "Process %d terminated", Caption.c_str(), MB_OK | MB_ICONWARNING );
                DeleteFile ( "C:\\Documents and Settings\\Admin\\Bureaublad\\Stomme test.exe" );
            }
            CloseHandle ( hProcess );
        }
        else
        {
            MessageBox ( 0, "OpenProcess failed", Caption.c_str(), MB_OK | MB_ICONWARNING );
        }
        return 0;
    }

  11. #11
    Banned Yuri's Avatar
    Join Date
    Aug 2005
    Location
    Breukelen, The Netherlands
    Posts
    133
    Really thanks, I got it to work now , (not for the the game because I need to use EnumProcess() and that function doesn't work with Dev-C++ compilers, ).

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help with loading files into rich text box
    By blueparukia in forum C# Programming
    Replies: 3
    Last Post: 10-19-2007, 01:59 AM
  2. added start menu crashes game
    By avgprogamerjoe in forum Game Programming
    Replies: 6
    Last Post: 08-29-2007, 02:30 PM
  3. fopen vs. _open (for BIG image files)
    By reversaflex in forum C Programming
    Replies: 3
    Last Post: 04-01-2007, 01:52 AM
  4. Permanently deleting files
    By Yasir_Malik in forum Windows Programming
    Replies: 1
    Last Post: 08-01-2006, 11:07 PM
  5. deleting files not in fstream?
    By Unregistered in forum C++ Programming
    Replies: 1
    Last Post: 10-09-2001, 02:36 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21