What is the most resource efficient method of a VB application responding to a new file being written to a directory (other than creating an NT service)?
Thanks
Printable View
What is the most resource efficient method of a VB application responding to a new file being written to a directory (other than creating an NT service)?
Thanks
If you're not afraid of timers, I have a simple solution,.
You can use the FindFirstChangeNotification API, ie.
[Edited by Aaron Young on 04-03-2000 at 02:53 PM]Code:Private Declare Function FindFirstChangeNotification Lib "kernel32" Alias "FindFirstChangeNotificationA" (ByVal lpPathName As String, ByVal bWatchSubtree As Long, ByVal dwNotifyFilter As Long) As Long
Private Declare Function WaitForSingleObject Lib "kernel32" (ByVal hHandle As Long, ByVal dwMilliseconds As Long) As Long
Private Const FILE_NOTIFY_CHANGE_FILE_NAME = &H1
Private Sub Form_Activate()
Dim lWait As Long
lWait = 1
While lWait
lWait = FindFirstChangeNotification("C:\Files", True, FILE_NOTIFY_CHANGE_FILE_NAME)
DoEvents
If WaitForSingleObject(lWait, 100) = 0 Then
Text1.SelText = "Something Changed." & vbCrLf
End If
Wend
End Sub
This will return all new files in a variant containing an array:
Calling this function the first time wont return anything. Calling it next time will return all new files that are added since then. Hope you get things work!Code:Function SearchDIR(directory)
On Error Resume Next 'oldfiles will cause subscript out of range the first time.
Static oldfiles() As String 'This static remains in memory after first function call
Dim newfiles() As String: ReDim newfiles(0) 'Temporary holds the new ones
Dim foundfiles() As String: ReDim foundfiles(0) 'The array to send in return
fil = Dir(directory, 7) 'Catch first file (hidden/system/archive files readen)
Do Until fil = ""
ReDim Preserve newfiles(UBound(newfiles) + 1) 'Resize array
newfiles(UBound(newfiles) - 1) = fil
For n = 0 To UBound(oldfiles) 'Search the old ones...
If fil = oldfiles(n) Then ' ... to test if fil is old
Exit For
End If
If n = UBound(oldfiles) Then '... if no matches, add to foundlist
ReDim Preserve foundfiles(UBound(foundfiles) + 1) 'Resize array
foundfiles(UBound(foundfiles) - 1) = fil 'Add
End If
Next n
fil = Dir() 'Find next file
Loop
ReDim oldfiles(UBound(newfiles) - 1) 'Removing last empty item in each array
ReDim Preserve newfiles(UBound(newfiles) - 1)
ReDim Preserve foundfiles(UBound(foundfiles) - 1)
For n = 0 To UBound(newfiles) ' Store filenames until next search
oldfiles(n) = newfiles(n)
Next n
SearchDIR = foundfiles() 'Return the found files in array
End Function