|
-
Mar 11th, 2008, 07:58 AM
#1
VB6 - Lock a Directory for Deleting
This shows how to lock a Directory so you can't delete it.
Windows will not allow you to delete a folder if a file is in use in that folder. Therefore the solution to locking a directory is simple, create a file, and keep it open, and while the file is open you cannot delete the directory.
But if you open a file with VB's built in functions, when you close the application, VB will automatically close the file pointers also. Therefore we have to use API because if you close the application, the file will still be opened.
Another problem is that if you open a file in that directory, the file will show up in Windows Explorer, and therefore we have to use ADS files.
So, finally, here's the code:
Put put 2 command buttons on the form, named "cmdLock" and "cmdUnlock".
As a sample, this code locks directory "C:\MyDirectory", but you can change it to whatever directory you need.
Code:
Option Explicit
Private Const OPEN_ALWAYS = 4
Private Const GENERIC_WRITE = &H40000000
Private Declare Function CreateFile Lib "kernel32" Alias "CreateFileA" (ByVal lpFileName As String, ByVal dwDesiredAccess As Long, ByVal dwShareMode As Long, ByVal lpSecurityAttributes As Long, ByVal dwCreationDisposition As Long, ByVal dwFlagsAndAttributes As Long, ByVal hTemplateFile As Long) As Long
Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
Public Function LockDir(ByVal Path As String) As Long
LockDir = CreateFile(Path & ":dirlock", GENERIC_WRITE, 0, 0, OPEN_ALWAYS, 0, 0)
End Function
Public Function UnlockDir(ByVal hDir As Long) As Boolean
UnlockDir = CloseHandle(hDir) <> 0
End Function
Private Sub Form_Load()
On Error Resume Next
MkDir "C:\MyDirectory"
End Sub
Private Sub cmdLock_Click()
Dim Ret As Long
Ret = Val(GetSetting(App.EXEName, "DirPointer", "Pointer", -1))
If Ret <> -1 And Ret <> 0 Then
cmdUnlock_Click
Else
Ret = LockDir("C:\MyDirectory")
If Ret <> -1 Then SaveSetting App.EXEName, "DirPointer", "Pointer", Ret
End If
End Sub
Private Sub cmdUnlock_Click()
Dim hDir As Long
hDir = Val(GetSetting(App.EXEName, "DirPointer", "Pointer", -1))
If hDir <> -1 And hDir <> 0 Then
If UnlockDir(hDir) Then SaveSetting App.EXEName, "DirPointer", "Pointer", -1
End If
End Sub
With this code you can only lock one directory at any time, becase it's saving the file pointer in only one registry location. But you can change the code to store the pointers in a Collection list, and save all the pointers to all the files opened.
Just remember that this code locks a Directory for deleting, not the files in it...
Last edited by CVMichael; Aug 25th, 2008 at 08:00 AM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|