![]() |
Desktop Development »
Shell and IE programming »
General
Intermediate
License: The Code Project Open License (CPOL)
Listing Used FilesBy NaveenA ShellExtension that lists all the used files in a folder |
VC6, Windows, Dev
|
|
Advanced Search |
|
|
|
||||||||||||||||
This is a utility to display all the files that are opened under a specific folder.
It often happens to me that when I try to rename or delete my current working folder of a project, it gives an error message like, "Cannot rename BlaBlaBla: It is being used by another person or program". Almost at all times, I fail to find this other program/person and end up restarting the machine. Since then, I have been searching for a method to find the list of files that an application uses. Even though the ProcessExplorer of SysInternals lists the files opened by each process, it is hard to find opened files in a particular folder. So I created one that does this, purely because of my necessity.
Download the application and register it using RegSvr32 (RegSvr32 OpenedFiles.dll). This application basically contains two components: an extension DLL and a driver. The extension DLL is responsible for showing the context menu in the shell and the GUI you see. I will explain the role of the driver later in this article.
This application will install a menu on folders, the background of a folder and on a drive. I suggest you read The Complete Idiot's Guide to Writing Shell Extensions - Part I, article by Michael Dunn, if you are new to shell extensions. In fact, it was from there that I learned to write shell extensions.
When you click on the "List Opened Files" menu, it will first enumerate all of the opened files in the system. This is implemented in the following function:
void MainDlg::EnumerateOpenedFiles( HANDLE hDriver )
{
...............
// Get the list of all handles in the system
PSYSTEM_HANDLE_INFORMATION pSysHandleInformation =
new SYSTEM_HANDLE_INFORMATION;
DWORD size = sizeof(SYSTEM_HANDLE_INFORMATION);
DWORD needed = 0;
NTSTATUS status = NtQuerySystemInformation
( SystemHandleInformation, pSysHandleInformation, size, &needed );
if( !NT_SUCCESS(status))
{
if( 0 == needed )
{
return;// some other error
}
// The previously supplied buffer wasn't enough.
delete pSysHandleInformation;
size = needed + 1024;
pSysHandleInformation = (PSYSTEM_HANDLE_INFORMATION)new BYTE[size];
status = NtQuerySystemInformation
SystemHandleInformation, pSysHandleInformation, size, &needed );
if( !NT_SUCCESS(status))
{
// some other error so quit.
delete pSysHandleInformation;
return;
}
}
int nCount = m_list.GetItemCount() - 1;
// Walk through the handle list
for ( DWORD i = 0; i < pSysHandleInformation->dwCount; i++ )
{
SYSTEM_HANDLE& sh = pSysHandleInformation->Handles[i];
if( sh.bObjectType != nFileType )
// Under Windows XP value of file handle type is 28 and
// in Windows Vista it is 25
{
continue;
}
HANDLE_INFO stHandle = {0};
ADDRESS_INFO stAddress;
stAddress.pAddress = sh.pAddress;
DWORD dwReturn = 0;
BOOL bSuccess = DeviceIoControl( hDriver,
IOCTL_LISTDRV_BUFFERED_IO, &stAddress, sizeof(ADDRESS_INFO),
&stHandle, sizeof(HANDLE_INFO), &dwReturn, NULL );
...
For every file opened in the system, there will be a handle associated with it. With the NtQuerySystemInformation API, we can retrieve all of the handles in the system. This includes file handles, Mutex handles, Event handles, etc. Actually, the NtQuerySystemInformation function returns an array of the structure SYSTEM_HANDLE.
typedef struct _SYSTEM_HANDLE
{
DWORD dwProcessId;
BYTE bObjectType;
BYTE bFlags;
WORD wValue;
PVOID pAddress;
DWORD GrantedAccess;
}
SYSTEM_HANDLE;
For an object of type file, the value bObjectType in SYSTEM_HANDLE is 28 in Windows XP, 25 in Windows Vista and 26 in Windows 2000.Since this application supports only XP/Vista, we can ignore all the items with values other than 28/25. In SYSTEM_HANDLE, there is another important member for us, the pAddress. For each file handle, there is a FILE_OBJECT associated with it and the pAddress is a pointer to that structure. Unfortunately, this address points to kernel memory space and a user mode application cannot access this memory. Here comes the role of a driver. Using the function DeviceIoControl, the pAddress is passed to the driver. The driver accepts this address and copies the file name from FILE_OBJECT, setting it in the out parameter of the DeviceIoControl function.
As I mentioned earlier, the process explorer shows the information about all the handles used by the application. However, the process explorer is a stand-alone application. So where is the driver? Or is it doing all this without the driver? This question puzzled me for many days until someone told me that the driver is added in the resource of the process explorer. Nice trick, isn't it? So I thought of implementing the same feature in my application too. The function given below performs this task:
HANDLE ExtractAndInstallDrv()
{
SC_HANDLE hSCManager =
OpenSCManager( NULL, NULL, SC_MANAGER_ALL_ACCESS );
SC_HANDLE hService = OpenService
( hSCManager , DRV_NAME, SERVICE_ALL_ACCESS);
CString csPath;
if( 0 == hService )
{
// Service not installed. So install the service.
// First extract the resource
HINSTANCE hModule= AfxGetInstanceHandle();
HRSRC hRsrc = FindResource
(hModule, MAKEINTRESOURCE(IDR_XPDRIVER),_T("BINARY"));
HGLOBAL hDrvRsrc = LoadResource(hModule, hRsrc);
DWORD dwDriverSize = SizeofResource(hModule, hRsrc);
LPVOID lpvDriver = LockResource(hDrvRsrc);
CFile File;
if( !File.Open( DRV_FILE_NAME, CFile::modeCreate|CFile::modeWrite ))
{
return 0;
}
File.Write( lpvDriver, dwDriverSize );
csPath = File.GetFilePath();
File.Close();
...
}
I made an application that does the above things and started using it. Some days later, again that rename problem occurred and my application listed nothing. When I looked in the task manager, I found out that this time it was because of the applications that were running from my folder. So my next step was to enumerate the EXEs and any DLLs that have been loaded from my folder.
Enumerating the modules loaded by applications was somewhat easy compared to the above task. It just made use of the following APIs. The EnumerateLoadedModules function handles this task in the application.
EnumProcesses()
CreateToolhelp32Snapshot()
Module32First()
Module32Next()
During the initial development of this utility, I purposefully ignored the option for closing any file handles opened by another process. I though it is unsafe if it provides such an option cause, closing the handle may lead to unexpected results in that application. However, I later got into some situations like the folder I want to rename is used by service.exe. And if I want to rename the folder, the only option is to terminate the process. But terminating the service.exe will make the entire system unstable. And so I was forced to include a Close Handle option too.
So how this option basically work is, it duplicates the handle using the DuplicateHandle() function with DUPLICATE_CLOSE_SOURCE flag specified. After that, it closes the duplicate handle also using the CloseHandle() function. This option will work only for loaded files, i.e. using this option on a DLL used by another process is just ignored.
HANDLE hDup = 0;
BOOL b = DuplicateHandle( hProcess, hFile, GetCurrentProcess(),
&hDup, DUPLICATE_SAME_ACCESS , FALSE, DUPLICATE_CLOSE_SOURCE );
if( hDup )
{
CloseHandle( hDup );
}
CloseHandle( hProcess );
Basically with the above code, we can close the handles created by another process.After closing the handle, we can rename or delete that file or directory. But there are cases where after closing the handle, we can rename the folder but deleting is not possible. For example, consider the file C:\WINDOWS\system32\config\CstEvent.Evt. Normally this file is used by the Service.exe for event logging purposes. So if we try to close this file handle using the above option, the handle will be closed and we can rename too, but cannot delete!! I tried many ways to solve this, but couldn't come up with a working solution. If anybody knows any other options to solve this, please let me know.
You have probably noticed that when we type some paths in the RUN Dialog of Windows, it will list the files and folders under that path. Similarly when you type a path in the combobox of this application, it will list the files and folder under that path. SHAutoComplete takes care of this feature. This function needs a handle of edit control. But I only have a combobox - how do I take the edit control inside it? Well, the edit control inside the combobox has control id 1001. So use the GetDlgItem() function with this ID to get the handle of the edit control. You can also specify a filename in that combobox.
BOOL MainDlg::OnInitDialog()
{
.....
CWnd* pEdit = m_combobox.GetDlgItem( 1001 );
if( pEdit )
{
SHAutoComplete( pEdit->m_hWnd, SHACF_FILESYSTEM );
}
}
When you right click on one item in the list control of this application, you will find a menu called "Find Target". This option is something like the find target option in Windows Explorer. It opens Windows Explorer window with a specified file selected in its folder. The SHOpenFolderAndSelectItems() is used for implementing this feature.
void MainDlg::OnMainFindtarget()
{
....
CString csPath;
csPath = m_list.GetItemText( nItem,2 );
LPITEMIDLIST stId = 0;
SFGAOF stSFGAOFIn = 0;
SFGAOF stSFGAOFOut = 0;
if( !FAILED(SHParseDisplayName( csPath, 0, &stId,stSFGAOFIn, &stSFGAOFOut )))
{
SHOpenFolderAndSelectItems( stId, 0, 0, 0 );
}
}
As mentioned above, the list control in the application lists includes two types of items - loaded files and loaded modules (DLLs, OCX, EXE etc.). This option is to Show/Hide one type of item from the list.
This application uses a drivers build for Windows XP/Vista and so it will run only on Windows XP/Vista. If you want, you can add support for other OS versions as well by building the driver.
General
News
Question
Answer
Joke
Rant
Admin
|
PermaLink |
Privacy |
Terms of Use
Last Updated: 6 Jun 2008 Editor: Deeksha Shenoy |
Copyright 2007 by Naveen Everything else Copyright © CodeProject, 1999-2009 Web17 | Advertise on the Code Project |