Question

Unlock / Release file (handle)?

Asked by: RBritz

Basically, this question has been asked before here on Experts-Exchange (http://www.experts-exchange.com/Programming/Languages/Pascal/Delphi/Q_21480486.html). What I would like to know is how this is done in code (Delphi)? I've googled, and read blogs for hours.... I've seen people say "it's not possible",  "kernel API monitor",  and explinations of how this "might" be possible... but no solution / code.

Any code (delphi) that might help me?

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-03-04 at 03:42:30ID24197065
Tags

Delphi

Topics

Kernel And Operating System Specific Programming

,

Windows Programming

Participating Experts
2
Points
500
Comments
16

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Pascal?
    What is Pascal, is it a relative to C
  2. Delphi and Turbo Pascal
    What are the major differences between Delphi and Turbo Pascal?
  3. Converting Pascal to Delphi
    Can I convert sources codes wroten in Turbo Pascal 6.0 to Delphi 2.0, and how?
  4. (borland) pascal for windows
    where is this programm ? where can i download this programm, or another pascal for windows programm.
  5. Converting Turbo Pascal's tpu into Delphi's dcu
    I want to programme that controls an IEEE card. Since this was a somewhat older card, the vendor supplied a pascal unit for Turbo Pascal 4.0. As ever the vendor only supplied the precompiled unit (*.tpu), which is completely incompatible with Delpi. Is there a way to comver...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: jkrPosted on 2009-03-04 at 07:47:17ID: 23795867

Basically it is not a good idea to forcibly close a file that is in use by another application - that might cause a crash or (even worse) data loss. If your goal is to delete a file in use, I'd rather recommend to use 'MoveFileEx()' (http://msdn.microsoft.com/en-us/library/aa365240(VS.85).aspx) with 'MOVEFILE_DELAY_UNTIL_REBOOT' to schedule the file to be deleted until the next reboot. See also http://support.microsoft.com/kb/140570 ("How To Move Files That Are Currently in Use")

 

by: RBritzPosted on 2009-03-11 at 01:38:13ID: 23854856

Sorry for the late response...

Basically the idea is to use it in a File Manager. I really hate that enoying Windows Message that pops up if you try and delete an empty folder (not a system folder) and it's still in use by some program...

Is there then a way to see which program is using(or locked)  the file/folder? Then maby the safest way is to prompt the user to close this application before continueing?

 

by: jkrPosted on 2009-03-11 at 13:09:29ID: 23861784

Well, that is definitely possible, but you'd need the Windows DDK (downloadable from http://www.microsoft.com/whdc/resources/downloads.mspx) for that, so I doubt that this can be done in Delphi. Anyway, the scoop would be the following (code taken from Gary Nebbett's "Native API Reference", http://books.google.com/books?id=Fp1ct-bKYdcC&printsec=frontcover)

#include <windows.h>
 
namespace NT
{
extern "C"
    {
#pragma warning (   disable:    4005)
        #include <basetsd.h>
        #include <ntdef.h>
        #include <ntstatus.h>
        #include <wdm.h>
#pragma warning (   default:    4005)
    }
 
 
 
extern "C"
NTSTATUS
__stdcall
ZwOpenDirectoryObject   (   PHANDLE,
                            ACCESS_MASK,
                            NT::POBJECT_ATTRIBUTES
                        );
extern "C"
NTSTATUS
__stdcall
ZwQueryDirectoryObject  (   HANDLE,
                            PVOID,
                            ULONG,
                            BOOLEAN,
                            BOOLEAN,
                            PULONG,
                            PULONG
                        );
 
typedef struct _DIRECTORY_BASIC_INFORMATION
{
  UNICODE_STRING    ObjectName;
  UNICODE_STRING    ObjectTypeName;
 
} DIRECTORY_BASIC_INFORMATION, *PDIRECTORY_BASIC_INFORMATION;
 
typedef enum _SYSTEM_INFORMATION_CLASS
{
    SystemHandleInformation = 16,
 
} SYSTEM_INFORMATION_CLASS;
 
typedef struct  _SYSTEM_HANDLE_INFORMATION
{
    ULONG       ProcessId;
    UCHAR       ObjectTypeNumber;
    UCHAR       Flags;
    USHORT      Handle;
    PVOID       Object;
    ACCESS_MASK GrantedAccess;
 
}   SYSTEM_HANDLE_INFORMATION,  *PSYSTEM_HANDLE_INFORMATION;
 
typedef enum _OBJECT_INFORMATION_CLASS
{
    ObjectBasicInformation,
    ObjectNameInformation,
    ObjectTypeInformation,
    ObjectAllTypesInformation,
    ObjectHandleInformation
}   OBJECT_INFORMATION_CLASS;
 
typedef struct  _OBJECT_BASIC_INFORMATION
{
    ULONG           Attributes;
    ACCESS_MASK     GrantedAccess;
    ULONG           HandleCount;
    ULONG           PointerCount;
    ULONG           PagedPoolUsage;
    ULONG           NonPagedPoolUsage;
    ULONG           Reserved    [   3];
    ULONG           NameInformationLength;
    ULONG           TypeInformationLength;
    ULONG           SecurityDescriptorLength;
    LARGE_INTEGER   CreateTime;
 
}   OBJECT_BASIC_INFORMATION,   *POBJECT_BASIC_INFORMATION;
 
 
typedef struct  _OBJECT_TYPE_INFORMATION
{
    UNICODE_STRING  Name;
    ULONG           ObjectCount;
    ULONG           HandleCount;
    ULONG           Reserved1   [   4];
    ULONG           PeakObjectCount;
    ULONG           PeakHandleCount;
    ULONG           Reserved2   [   4];
    ULONG           InvalidAttributes;
    GENERIC_MAPPING GenericMapping;
    ULONG           ValidAccess;
    UCHAR           Unknown;
    BOOLEAN         MaintainHandleDatabase;
    NT::POOL_TYPE   PoolType;
    ULONG           PagedPoolUsage;
    ULONG           NonPagedPoolUsage;
 
}   OBJECT_TYPE_INFORMATION,    *POBJECT_TYPE_INFORMATION;
 
 
extern "C"
NTSTATUS
__stdcall
ZwQuerySystemInformation    (   SYSTEM_INFORMATION_CLASS,
                                PVOID,
                                ULONG,
                                PULONG
                            );
 
extern "C"
NTSTATUS
__stdcall
ZwQueryObject               (   HANDLE,
                                OBJECT_INFORMATION_CLASS,
                                PVOID,
                                ULONG,
                                PULONG
                            );
 
 
extern "C"
NTSTATUS
__stdcall
ZwDuplicateObject           (   HANDLE,
                                HANDLE,
                                HANDLE,
                                PHANDLE,
                                ACCESS_MASK,
                                ULONG,
                                ULONG
                            );
 
}; // namespace
 
using NT::NTSTATUS;
using NT::UNICODE_STRING;
using NT::PUNICODE_STRING;
using NT::OBJECT_ATTRIBUTES;
 
#include <stdlib.h>
#include <stdio.h>
 
 
#define DUPLICATE_SAME_ATTRIBUTES   0x00000004
 
#define NtCurrentProcess() ( (HANDLE) -1 )
 
#pragma comment(lib,"ntdll.lib")
#pragma comment(lib,"advapi32.lib")
 
BOOL EnablePrivilege(PCSTR name)
{
    TOKEN_PRIVILEGES priv = {1, {0, 0, SE_PRIVILEGE_ENABLED}};
    LookupPrivilegeValue(0, name, &priv.Privileges[0].Luid);
 
    HANDLE hToken;
    OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken);
 
    AdjustTokenPrivileges(hToken, FALSE, &priv, sizeof priv, 0, 0);
    BOOL rv = GetLastError() == ERROR_SUCCESS;
 
    CloseHandle(hToken);
    return rv;
}
 
int main(int argc, char *argv[])
{
    if (argc == 1) return 0;
 
    ULONG pid = strtoul(argv[1], 0, 0);
 
    EnablePrivilege(SE_DEBUG_NAME);
 
    HANDLE hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, pid);
 
    ULONG n = 0x1000;
    PULONG p = new ULONG[n];
 
    while (NT::ZwQuerySystemInformation(NT::SystemHandleInformation, p, n * sizeof *p, 0)
           == STATUS_INFO_LENGTH_MISMATCH)
 
        delete [] p, p = new ULONG[n *= 2];
 
    NT::PSYSTEM_HANDLE_INFORMATION h = NT::PSYSTEM_HANDLE_INFORMATION(p + 1);
 
    for (ULONG i = 0; i < *p; i++) {
 
        if (h[i].ProcessId == pid) {
            HANDLE hObject;
 
            if (NT::ZwDuplicateObject(hProcess, HANDLE(h[i].Handle), NtCurrentProcess(), &hObject,
                                      0, 0, DUPLICATE_SAME_ATTRIBUTES)
                != STATUS_SUCCESS) continue;
 
            NT::OBJECT_BASIC_INFORMATION obi;
 
            NT::ZwQueryObject(hObject, NT::ObjectBasicInformation, &obi, sizeof obi, &n);
 
            printf("%p %04hx %6lx %2x %3lx %3ld %4ld ",
                   h[i].Object, h[i].Handle, h[i].GrantedAccess,
                   int(h[i].Flags), obi.Attributes,
                   obi.HandleCount - 1, obi.PointerCount - 2);
 
            n = obi.TypeInformationLength + 2;
 
            NT::POBJECT_TYPE_INFORMATION oti = NT::POBJECT_TYPE_INFORMATION(new CHAR[n]);
 
            NT::ZwQueryObject(hObject, NT::ObjectTypeInformation, oti, n, &n);
 
            printf("%-14.*ws ", oti[0].Name.Length / 2, oti[0].Name.Buffer);
 
            n = obi.NameInformationLength == 0
                ? MAX_PATH * sizeof (WCHAR) : obi.NameInformationLength;
 
            NT::POBJECT_NAME_INFORMATION oni = NT::POBJECT_NAME_INFORMATION(new CHAR[n]);
 
            NTSTATUS rv = NT::ZwQueryObject(hObject, NT::ObjectNameInformation, oni, n, &n);
            if (NT_SUCCESS(rv))
                printf("%.*ws", oni[0].Name.Length / 2, oni[0].Name.Buffer);
 
            printf("\n");
 
            CloseHandle(hObject);
        }
    }
    delete [] p;
 
    CloseHandle(hProcess);
 
    return 0;
}

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
176:
177:
178:
179:
180:
181:
182:
183:
184:
185:
186:
187:
188:
189:
190:
191:
192:
193:
194:
195:
196:
197:
198:
199:
200:
201:
202:
203:
204:
205:
206:
207:
208:
209:
210:
211:
212:
213:
214:
215:
216:
217:
218:
219:
220:
221:
222:
223:
224:
225:
226:
227:
228:
229:
230:
231:
232:
233:
234:
235:
236:
237:

Select allOpen in new window

 

by: RBritzPosted on 2009-03-12 at 01:33:33ID: 23865856

Hey jkr

Thanks for assisting me!  

The following file has some of the functions mentioned above (in your code snippet). Do you think this might help

I've found this source code at http://w-shadow.com/blog/2006/10/19/listing-all-open-handles/

My knowledge of C is very limited at the moment...

unit untdefs;
 
interface
 
uses Windows, SysUtils, PSApi;
 
type
 NTSTATUS=cardinal;
 POBJECT=pointer;
 
 USHORT=word;
 
 SYSTEM_HANDLE=packed record
	uIdProcess:ULONG;
	ObjectType:UCHAR;    // OB_TYPE_* (OB_TYPE_TYPE, etc.)
	Flags:UCHAR;         // HANDLE_FLAG_* (HANDLE_FLAG_INHERIT, etc.)
	Handle:USHORT;
	pObject:PObject;
	GrantedAccess:ACCESS_MASK;
 end;
 PSYSTEM_HANDLE=^SYSTEM_HANDLE;
 SYSTEM_HANDLE_ARRAY=array[0..0] of SYSTEM_HANDLE;
 PSYSTEM_HANDLE_ARRAY=^SYSTEM_HANDLE_ARRAY;
 
 SYSTEM_HANDLE_INFORMATION=packed record
	uCount:ULONG;
	Handles:SYSTEM_HANDLE_ARRAY;
 end;
 PSYSTEM_HANDLE_INFORMATION=^SYSTEM_HANDLE_INFORMATION;
 
 UNICODE_STRING=packed record
    Length:USHORT;
    MaximumLength:USHORT;
    Buffer:PWideChar;
 end;
 PUNICODE_STRING=^UNICODE_STRING;
 
 OBJECT_NAME_INFORMATION=UNICODE_STRING;
 POBJECT_NAME_INFORMATION=^OBJECT_NAME_INFORMATION;
 
 SYSTEM_INFORMATION_CLASS=(
  SystemBasicInformation,       // 0x002C
  SystemProcessorInformation,     // 0x000C
  SystemPerformanceInformation,    // 0x0138
  SystemTimeInformation,       // 0x0020
  SystemPathInformation,       // not implemented
  SystemProcessInformation,      // 0x00F8+ per process
  SystemCallInformation,       // 0x0018 + (n * 0x0004)
  SystemConfigurationInformation,   // 0x0018
  SystemProcessorCounters,      // 0x0030 per cpu
  SystemGlobalFlag,          // 0x0004
  SystemInfo10,            // not implemented
  SystemModuleInformation,      // 0x0004 + (n * 0x011C)
  SystemLockInformation,       // 0x0004 + (n * 0x0024)
  SystemInfo13,            // not implemented
  SystemPagedPoolInformation,     // checked build only
  SystemNonPagedPoolInformation,   // checked build only
  SystemHandleInformation,      // 0x0004 + (n * 0x0010)
  SystemObjectInformation,      // 0x0038+ + (n * 0x0030+)
  SystemPagefileInformation,     // 0x0018+ per page file
  SystemInstemulInformation,     // 0x0088
  SystemInfo20,            // invalid info class
  SystemCacheInformation,       // 0x0024
  SystemPoolTagInformation,      // 0x0004 + (n * 0x001C)
  SystemProcessorStatistics,     // 0x0000, or 0x0018 per cpu
  SystemDpcInformation,        // 0x0014
  SystemMemoryUsageInformation1,   // checked build only
  SystemLoadImage,          // 0x0018, set mode only
  SystemUnloadImage,         // 0x0004, set mode only
  SystemTimeAdjustmentInformation,  // 0x000C, 0x0008 writeable
  SystemMemoryUsageInformation2,   // checked build only
  SystemInfo30,            // checked build only
  SystemInfo31,            // checked build only
  SystemCrashDumpInformation,     // 0x0004
  SystemExceptionInformation,     // 0x0010
  SystemCrashDumpStateInformation,  // 0x0008
  SystemDebuggerInformation,     // 0x0002
  SystemThreadSwitchInformation,   // 0x0030
  SystemRegistryQuotaInformation,   // 0x000C
  SystemLoadDriver,          // 0x0008, set mode only
  SystemPrioritySeparationInformation,// 0x0004, set mode only
  SystemInfo40,            // not implemented
  SystemInfo41,            // not implemented
  SystemInfo42,            // invalid info class
  SystemInfo43,            // invalid info class
  SystemTimeZoneInformation,     // 0x00AC
  SystemLookasideInformation,     // n * 0x0020
// info classes specific to Windows 2000
// WTS = Windows Terminal Server
  SystemSetTimeSlipEvent,       // set mode only
  SystemCreateSession,        // WTS, set mode only
  SystemDeleteSession,        // WTS, set mode only
  SystemInfo49,            // invalid info class
  SystemRangeStartInformation,    // 0x0004
  SystemVerifierInformation,     // 0x0068
  SystemAddVerifier,         // set mode only
  SystemSessionProcessesInformation // WTS
  );
 
 OBJECT_INFORMATION_CLASS = (
	ObjectBasicInformation,
	ObjectNameInformation,
	ObjectTypeInformation,
	ObjectAllTypesInformation,
	ObjectHandleInformation
 );
 
 TNTQuerySystemInformation=function
  (SystemInformationClass:DWORD;
   SystemInformation:pointer;
   SystemInformationLength:DWORD;
   ReturnLength:PDWORD
   ):NTSTATUS; stdcall;
 
 TNTQueryObject=function(
  ObjectHandle:cardinal;
  ObjectInformationClass:OBJECT_INFORMATION_CLASS;
  ObjectInformation:pointer;
  Length:ULONG;
  ResultLength:PDWORD
  ):NTSTATUS;stdcall;  
 
const
 STATUS_SUCCESS:NTSTATUS	= $00000000;
 STATUS_INFO_LENGTH_MISMATCH:NTSTATUS = $C0000004;
 STATUS_BUFFER_OVERFLOW:NTSTATUS	= $80000005;
 
function EnableDebugPrivilege:boolean;
function GetObjectInfo(hObject:cardinal;
 objInfoClass:OBJECT_INFORMATION_CLASS):LPWSTR;
function  GetFileNameFromHandle(hFile:Cardinal):string;
 
var
 NTQueryObject:TNTQueryObject;
 NTQuerySystemInformation:TNTQuerySystemInformation;
 
 
implementation
 
function EnableDebugPrivilege:boolean;
var
	hToken:cardinal;
	tokenPriv:TOKEN_PRIVILEGES;
	luidDebug:TLargeInteger;
  rlen:cardinal;
begin
  result:=false;
	if OpenProcessToken(GetCurrentProcess(),
      TOKEN_ADJUST_PRIVILEGES,
      hToken) then begin
		if LookupPrivilegeValue( nil , 'SeDebugPrivilege', luidDebug) then
		begin
			tokenPriv.PrivilegeCount := 1;
			tokenPriv.Privileges[0].Luid := luidDebug;
			tokenPriv.Privileges[0].Attributes := SE_PRIVILEGE_ENABLED;
			result:=AdjustTokenPrivileges(hToken, FALSE, tokenPriv,
        sizeof(tokenPriv), nil, rlen);
		end;
	end;
end;
 
function GetObjectInfo(hObject:cardinal;
 objInfoClass:OBJECT_INFORMATION_CLASS):LPWSTR;
var
 dwSize:DWORD;
 pObjectInfo:POBJECT_NAME_INFORMATION;
 ntReturn:NTSTATUS;
begin
  result:=nil;
	if(@NTQuerySystemInformation<>nil) then begin
		dwSize := sizeof(OBJECT_NAME_INFORMATION);
		pObjectInfo := AllocMem(dwSize);
		ntReturn := NTQueryObject(hObject, objInfoClass, pObjectInfo,
     dwSize, @dwSize);
		if((ntReturn = STATUS_BUFFER_OVERFLOW) or
       (ntReturn = STATUS_INFO_LENGTH_MISMATCH)) then begin
			FreeMem(pObjectInfo);
			pObjectInfo := AllocMem(dwSize);
			ntReturn := NTQueryObject(hObject, objInfoClass, pObjectInfo,
       dwSize, @dwSize);
		end;
		if((ntReturn >= STATUS_SUCCESS) and (pObjectInfo.Buffer <> nil)) then
		begin
			result := AllocMem(pObjectInfo.Length + sizeof(WCHAR));
			CopyMemory(result, pObjectInfo.Buffer, pObjectInfo.Length);
		end;
		FreeMem(pObjectInfo);
	end;
end;
 
function  GetFileNameFromHandle(hFile:Cardinal):string;
const
 BUFSIZE=512;
var
 bFound:boolean;
 pszFilename,
 szTemp,
 szDrive,
 szName:PAnsiChar;
 p:PAnsiChar;
 hFileMap,uNameLen:Cardinal;
 dwFileSizeHi, dwFileSizeLo:DWORD;
 pMem:pointer;
begin
   result:='';
   //  Get  the  file  size.
   dwFileSizeHi  :=  0;
   dwFileSizeLo  :=  GetFileSize(hFile,  @dwFileSizeHi);
 
   if ((dwFileSizeLo  =  0)  and  (dwFileSizeHi  =  0)) then exit;
 
   pszFilename:=AllocMem(MAX_PATH*2+2);
   szTemp:=AllocMem(BUFSIZE);
   szName:=AllocMem(MAX_PATH);
 
   //  Create  a  file  mapping  object.
   hFileMap  :=  CreateFileMapping(hFile,
                     nil,
                     PAGE_READONLY,
                     0,
                     1,
                     nil);
 
    if  (hFileMap<>0) then begin
    //  Create  a  file  mapping  to  get  the  file  name.
    pMem  :=  MapViewOfFile(hFileMap,  FILE_MAP_READ,  0,  0,  1);
     if  (pMem<>nil) then begin
       if  GetMappedFileName (GetCurrentProcess(),  
                              pMem,  
                              pszFilename, 
                              MAX_PATH)<>0 then
       begin
          //  Translate  path  with  device  name  to  drive  letters. 
          if  (GetLogicalDriveStrings(BUFSIZE-1,  szTemp)<>0) then begin
           bFound  :=  FALSE;
           p  :=  szTemp;
           repeat
             //  Copy  the  drive  letter  to  the  template  string
             szDrive  :=  p; 
             //  Look  up  each  device  name
             if  QueryDosDevice(szDrive,  szName,  BUFSIZE)<>0 then begin
              uNameLen  :=  length(szName);
              if  (uNameLen  <  MAX_PATH) then begin
                bFound  := AnsiStrLComp(pszFilename, szName,uNameLen)=0;
 
                if  (bFound) then begin
                   //  Reconstruct  pszFilename  using  szTemp
                   //  Replace  device  path  with  DOS  path
                   result:=Format('%s%s',
                             [szDrive,
                             PAnsiChar(cardinal(pszFilename)+
                             uNameLen)]);
                end;
              end;
             end;
 
            //  Go  to  the  next  NULL  character.
            while ( p^<>#0 ) do inc(p);
           until bFound or (p^=#0);
         end;
       end;
       UnmapViewOfFile(pMem); 
     end;  
 
      CloseHandle(hFileMap); 
   end;
 
   FreeMem(pszFilename);
   FreeMem(szTemp);
   FreeMem(szName);
end;
 
begin
 NTQueryObject := GetProcAddress(
  GetModuleHandle('NTDLL.DLL'), 'NtQueryObject');
 NTQuerySystemInformation := GetProcAddress(
  GetModuleHandle('NTDLL.DLL'), 'NtQuerySystemInformation');
end.

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
176:
177:
178:
179:
180:
181:
182:
183:
184:
185:
186:
187:
188:
189:
190:
191:
192:
193:
194:
195:
196:
197:
198:
199:
200:
201:
202:
203:
204:
205:
206:
207:
208:
209:
210:
211:
212:
213:
214:
215:
216:
217:
218:
219:
220:
221:
222:
223:
224:
225:
226:
227:
228:
229:
230:
231:
232:
233:
234:
235:
236:
237:
238:
239:
240:
241:
242:
243:
244:
245:
246:
247:
248:
249:
250:
251:
252:
253:
254:
255:
256:
257:
258:
259:
260:
261:
262:
263:
264:
265:
266:
267:
268:
269:
270:
271:
272:
273:
274:
275:
276:
277:
278:

Select allOpen in new window

 

by: jkrPosted on 2009-03-12 at 12:02:48ID: 23872215

Hm, that pretty much looks like what you would need...

 

by: jkrPosted on 2009-03-13 at 08:43:17ID: 23880525

Um, you got the code for doing what you need and flag that as "No acceptable solution supplied" - sorry, is this a joke?

 

by: RBritzPosted on 2009-03-16 at 01:05:56ID: 23895408

Joke? I asked for any code (In Delphi) to do this! Do you see any code that you supplied written in Delphi!?

Quote: "Um, you got the code for doing what you need and flag that as...";  Do you mean the code I found by searching 100's of pages? Or do you mean the code you supplied which was in C?

Now then, if you really want the 500 points, then earn it. I'll keep the question open.

The code I supplied above, how will it help me then? Will the open file contain the same Handle as the Application?

 

by: MidnicPosted on 2009-03-16 at 10:19:54ID: 23900055

I've never seen any Delphi code that can do this, but I doubt that it is impossible.

You may want to create a seperate thread to check the file at a specific interval. Once the file has been unlocked, you can delete it. I've attached a code snippit that will check if the file is in use. I've found this somewhere on the web (delphi pages i think, or maybe torry.net)

function IsFileInUse(const fName: TFileName): Boolean;
var
    HFileRes: HFILE;
 
begin
    Result := False;
    HFileRes := CreateFile(PChar(fName),
                GENERIC_READ or GENERIC_WRITE,
                0,
                nil,
                OPEN_EXISTING,
                FILE_ATTRIBUTE_NORMAL,
                0);
 
   Result := (HFileRes = INVALID_HANDLE_VALUE);
 
   if not Result then
       CloseHandle(HFileRes);
 
end;

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

Select allOpen in new window

 

by: jkrPosted on 2009-03-16 at 10:24:47ID: 23900114

Hm, you wfound the Delphi source code after I provided the function names in the C sample. I do indeed doubt that you'd have found it without the C example.

 

by: RBritzPosted on 2009-03-17 at 01:45:32ID: 23905670

Hi Midnic,

Yes, that was my original idea until I saw/noticed a utility called "Unlock Assistant". So your Idea is good, but not quite what I'm looking for. I want to be able to inform the user which program is using the file, and that they should close it inorder to delete the file. My original idea was to delete/release the handle, but jkr informed me this is too dangerous. Any ideas?

jkr: Lmao, no comment bro

 

by: MidnicPosted on 2009-03-18 at 09:44:18ID: 23920715

RBritz,

I haven't forgotten your question, I'm working on it.... ;)

 

by: MidnicPosted on 2009-03-18 at 09:45:40ID: 23920723

BTW, I've downloaded the program, works pretty well..

 

by: RBritzPosted on 2009-03-18 at 23:09:53ID: 23926776

OMG, Vee Mod, Are you surious!? Do you actually classify laughing and having no comment as a "wise crack" and a "cheap shot"!? If my intend was to take a cheap shot, or use wise cracks, it wouldn't be something as simple as laughing!

And what's your reason for a accepting the solution? Midnic is still trying to help!?

 

by: MidnicPosted on 2009-03-20 at 10:08:37ID: 23941421

Ok, this is quite childish...

RBritz, I've got a working demo for you, let me know

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...