Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
 
  HOME    TRACKER    Visual Basic




FindNextFile


Hi!!
i have this code:

hSearch = FindFirstFile(path & "*", WFD)
If hSearch <> INVALID_HANDLE_VALUE Then
While hSearch
FileName = WFD.cFileName
If (FileName <> ".") And (FileName <> "..") And (FileName <> "") Then
sFileExist = path & FileName
sFileNew = path2 & FileName

lResult = CopyFile(sFileExist, sFileNew, False)
End If

hSearch = FindNextFile(hSearch, WFD)
Wend
hSearch = FindClose(hSearch)
End If


and my problem is that FindNextFile finds ".", ".." and then anything else.
In that folder I have 2 files (I'm sure 100%) called Ar.1 and Ar.2.

If i search "path & "*.1"" the FindFirstFile finds Ar.1.

Why??? what is wrong?

thank you




View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
Issues With FindNextFile API.
Hi there,

I am having a problem with the FindNextFile API. I basicly run it in a loop, and perform various operations on the file. What seems to be happening, is after about 3000 files, I get a nasty Windows error that points toward running out of files to use.

I think what is happening, is that something in the code is not releasing the file after it is complete. I store the details of FindNextFile in a myType structure, as defined by the API.

Does this structure need to be cleared out after each file? And if so, is clearing a structure as easy as myType = nothing?

Maybe I am missing something about the FindNextFile, perhaps there is a better way of doing this. Using an fso object is just way to slow for the kind of file transactions I am going to be handling.

Let me know if you want me to paste code examples. I could really use some help with this.


Many Thanks

DBridle

How Do I Use The FindFirstFile/FindNextFile To Get Names Of The Files In The C:?
How do i use the FindFirstFile/FindNextFile to get names of the files in the c:?

Several Problems (LockWindowUpdate + DoEvents, FindNextFile)
Hello!

I am experiencing some problems with the following things:

1. LockWindowUpdate together with DoEvents
2. Using FindNextFile for finding files based on multiple patterns.

For problem 1:

I have the following code placed inside a class module:


Code:
Option Explicit

Public Enum QueueMessages
All_Inputs = &HFF
All_Events = &HBE
Standard = &HA5
Messages = &H48
InputOnly = &H6
Mouse = &H6
MouseMove = &H2
Timer = &H10
End Enum

Private Declare Function GetQueueStatus Lib "user32" (ByVal fuFlags As Long) As Long

Private enuQeueMessage As QueueMessages

Public Sub GetInputState()

If Not GetQueueStatus(enuQeueMessage) = 0 Then
DoEvents
End If

End Sub

Public Property Let QueueUsed(ByVal enuData As QueueMessages)

enuQeueMessage = enuData

End Property

Public Property Get QueueUsed() As QueueMessages

QueueUsed = enuQeueMessage

End Property

It checks whether or not events are queued and if so, it triggers DoEvents. The problem is that I have a pretty big loop which causes the form to stop reacting. If I use GetInputState, DoEvents will be triggered whenever events are pending (defined in enuQeueMessage). Everything works perfectly and the form gets redrawed any everything when needed. However, I would like to keep a certain part of the window from being updated. LockWindowUpdate works, but not together with DoEvents. Any idea how I could make both work?

For problem 2... I am using the API-Guide example for searching files. I was wondering if it is possible to search for files using multiple patterns in only one run. For example, I want to add all WAV, MP1, MP2, MP3 and Ogg Vorbis files to a list. At the moment, I am calling the import function 5 times. If a user adds his whole C: drive for example, the function will parse C: and its subfolders 5 times. It would be better to do that in only one run, but I don't know how.

Regards,
Sebastian Mares

Cant Get Findfirst File And Findnextfile To Work In Vb 2005
i am trying to to get files in vb 2005 using the findfirstfile and findnextfile api but cant get it to work in vb 2005


Code:

Private Declare Function GetTempPath Lib "kernel32" Alias "GetTempPathA" (ByVal nBufferLength As Integer, ByVal lpBuffer As String) As Integer
Private Declare Function FindFirstFile Lib "kernel32" Alias "FindFirstFileA" (ByVal lpFileName As String, ByRef lpFindFileData As WIN32_FIND_DATA) As Integer
Private Declare Function FindNextFile Lib "kernel32" Alias "FindNextFileA" (ByVal hFindFile As Integer, ByRef lpFindFileData As WIN32_FIND_DATA) As Integer
Private Declare Function GetFileAttributes Lib "kernel32" Alias "GetFileAttributesA" (ByVal lpFileName As String) As Integer
Private Declare Function FindClose Lib "kernel32" (ByVal hFindFile As Integer) As Integer
Private Structure FILETIME
Dim dwLowDateTime As Long
Dim dwHighDateTime As Long
End Structure
Private Structure WIN32_FIND_DATA
Dim dwFileAttributes As Integer
Dim ftCreationTime As FILETIME
Dim ftLastAccessTime As FILETIME
Dim ftLastWriteTime As FILETIME
Dim nFileSizeHigh As Integer
Dim nFileSizeLow As Integer
Dim dwReserved0 As Integer
Dim dwReserved1 As Integer
<VBFixedString(MAX_PATH), System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst:=MAX_PATH)> Dim cFileName As String
<VBFixedString(14), System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst:=14)> Dim cAlternate As String
End Structure
Private Const MAX_PATH As Short = 260
Private Const INVALID_HANDLE_VALUE As Short = -1
Private Const FILE_ATTRIBUTE_ARCHIVE As Short = &H20
Private Const FILE_ATTRIBUTE_DIRECTORY As Short = &H10
Private Const FILE_ATTRIBUTE_HIDDEN As Short = &H2
Private Const FILE_ATTRIBUTE_NORMAL As Short = &H80
Private Const FILE_ATTRIBUTE_READONLY As Short = &H1
Private Const FILE_ATTRIBUTE_SYSTEM As Short = &H4
Private Const FILE_ATTRIBUTE_TEMPORARY As Short = &H100

Public Shared Function GetFiles() As String
Dim FileName As String
Dim i As Integer
Dim hSearch As Integer
Dim WFD As WIN32_FIND_DATA
WFD.cFileName = New String(ch4r(0), MAX_PATH)
WFD.cAlternate = New String(ch4r(0), 14)
Dim cont As Integer
hSearch = FindFirstFile("c:" & "*.", WFD)
cont = 1
While cont >= 1
If WFD.dwFileAttributes <> FILE_ATTRIBUTE_DIRECTORY Then
FileName = Left(WFD.cFileName.ToString, WFD.cFileName.Length)
If (FileName <> ".") And (FileName <> "..") Then
FrmMain.RtxtPromt.Text = FrmMain.RtxtPromt.Text & FileName & vbCrLf
End If
End If
cont = FindNextFile(hSearch, WFD)
End While
End Function
i get the file attributes but not getting the file name

FindNextFile, UNC Paths And Running As A Service Returns '-1'
I've run into a very strange problem regarding the FindFirstFile and FindNextFile API call. I created an application that uses the function below to retrieve a list of files and store them. If I assign a UNC Path, this works fine as long as the application runs as a standard .exe. However, if I try starting the application using the NT Service control (Under Windows XP SP1) the FindNextFile API returns a '-1' consistently.

My thought is that this is an OS limitation that is intentionally prohibiting the code from running to avoid possible Trojan/Virus from spreading. However, I was wondering if anyone has run into this or knows of a workaround.

Here's the main portion of the code, much of it came from Microsoft's knowledge base...

The line below "hSearch = FindFirstFile(sDirSpec & sSpec, WFD)" returns a '-1' if the directory being searched is a UNC Path and the app. is running as a service. If scanning a local folder as a standard .exe, it returns the correct file handle.


VB Code:
Public Function LoadFiles( _                        ByVal path As String, _                        Optional ByVal bRecursive As Boolean = False, _                        Optional ByVal pb) _                As Long                Dim dircount As LongDim FileName As String   ' Walking filename variable...Dim DirName As String    ' SubDirectory NameDim dirNames() As String ' Buffer for directory name entriesDim nDir As Integer   ' Number of directories in this pathDim i As Integer      ' For-loop counter...Dim hSearch As Long   ' Search HandleDim WFD As WIN32_FIND_DATADim Cont As IntegerDim FT As FILETIMEDim ST As SYSTEMTIMEDim DateCStr As String, DateMStr As StringDim sFileSpec As StringDim sDirSpec As StringDim sSpec As StringDim fileCount As Long     sSpec = ts.sFilename(path, efpFileNameAndExt)    sDirSpec = ts.sAppend(ts.sFilename(path, efpFilePath), "")      ' Search subdirectories if necessary   If bRecursive = True Then        ' Search for subdirectories.        nDir = 0        ReDim dirNames(nDir)        Cont = True        hSearch = FindFirstFile(sDirSpec & "*", WFD)                If hSearch <> INVALID_HANDLE_VALUE Then           Do While Cont              DirName = StripNulls(WFD.cFileName)              ' Ignore the current and encompassing directories.              If (DirName <> ".") And (DirName <> "..") Then                 ' Check for directory with bitwise comparison.                 If GetFileAttributes(sDirSpec & DirName) And _                  FILE_ATTRIBUTE_DIRECTORY Then                    dirNames(nDir) = DirName                    dircount = dircount + 1                    nDir = nDir + 1                    ReDim Preserve dirNames(nDir)                  End If              End If              Cont = FindNextFile(hSearch, WFD)  ' Get next subdirectory.           Loop           Cont = FindClose(hSearch)        End If    End If        ' Walk through this directory and sum file sizes.   hSearch = FindFirstFile(sDirSpec & sSpec, WFD)   Cont = True        ' The value of 'hSearch' is '-1' when this code is run as a service and is scanning a UNC Path.    'MsgBox hSearch      If hSearch <> INVALID_HANDLE_VALUE Then    Cont = True      While Cont         FileName = StripNulls(WFD.cFileName)            If (FileName <> ".") And (FileName <> "..") And _              ((GetFileAttributes(sDirSpec & FileName) And _               FILE_ATTRIBUTE_DIRECTORY) <> FILE_ATTRIBUTE_DIRECTORY) Then                                          LoadFiles = LoadFiles + (WFD.nFileSizeHigh * _             MAXDWORD) + WFD.nFileSizeLow            fileCount = fileCount + 1                                   Set oFile = New clsFile            oFile.sFilename = ts.sFilename(sDirSpec, efpFilePath) & StripNulls(ts.sNT(WFD.cFileName))            mCol.Add oFile          End If         Cont = FindNextFile(hSearch, WFD)  ' Get next file      Wend      Cont = FindClose(hSearch)   End If     LoadFiles = mCol.Count End Function

Converting Time Returned With FindFirstFile / FindNextFile API
I'm trying to figure out what I'm doing wrong with the conversion of the UTC values to standard time format.

I can seem to get the correct date, but the time always seems to be a little off.

I'm getting the info with the following:-


Code:
Private Type FILETIME
dwLowDateTime As Long
dwHighDateTime As Long
End Type

Private Type WIN32_FIND_DATA
dwFileAttributes As Long
ftCreationTime As FILETIME
ftLastAccessTime As FILETIME
ftLastWriteTime As FILETIME
nFileSizeHigh As Long
nFileSizeLow As Long
dwReserved0 As Long
dwReserved1 As Long
cFileName As String * MAX_PATH
cAlternate As String * 14
End Type

'in function
hFile = FindFirstFile(sRoot & ALL_FILES, WFD)


Then I'm trying to pass the individual values across to a function:-


Code:
'calling code
.FileLastAccess = ConvDateTime(WFD.ftLastAccessTime)

'function
Public Function ConvDateTime(FtInput As FILETIME) As FileSearchTime

Dim LFTime As FILETIME
Dim SysTime As SYSTEMTIME

If FtInput.dwHighDateTime = 0 And FtInput.dwLowDateTime = 0 Then
ConvDateTime.fstDate = Empty
ConvDateTime.fstTime = "Unknown"
Else
'FileTimeToLocalFileTime FtInput, LFTime
FileTimeToSystemTime FtInput, SysTime

ConvDateTime.fstDate = Str$(SysTime.wDay) + "/" + LTrim(Str$(SysTime.wMonth)) + "/" + LTrim(Str$(SysTime.wYear))
ConvDateTime.fstTime = Str$(SysTime.wHour) + ":" + LTrim(Str$(SysTime.wMinute)) + ":" + LTrim(Str$(SysTime.wSecond))
End If

End Function

'types I've used here
Private Type SYSTEMTIME
wYear As Integer
wMonth As Integer
wDayOfWeek As Integer
wDay As Integer
wHour As Integer
wMinute As Integer
wSecond As Integer
wMilliseconds As Integer
End Type

Private Type FileSearchTime
fstDate As Date
fstTime As String
End Type


As you can see ... I'm using the FileTimeToSystemTime API, and have tried out the FileTimeToLocalFileTime API, neither giving the time I find in explorer. Perhaps I'm coming at this all wrong ... Any Ideas.

Oh ... when I was testing the FileTimeToLocalFileTime API, the second conversion read:-

Code:
FileTimeToSystemTime LFTime, SysTime


Any help here would be great.

FindFirstFile/FindNextFile - Weird Results (how To Define WIN32_FIND_DATA?)
Hello,

The following code enumerates all files/folders in a given path.
It seems to work ok, but some strange things occur depending on the definition of WIN32_FIND_DATA:

Using the format in the code below the application will instantly shut down after the End Sub of the Main sub. (VB practically disappears...) [cFileName(MAX_PATH), cAlternateFileName(14)]

If I were to increse the byte arrays size times 2, everything runs fine. [cFileName(MAX_PATH*2), cAlternateFileName(14*2)]

After taking down their size by 10 each, I get an Error 49 - 'Bad Dll calling convention'. But where does the error pop up, after End Sub of EnumFilesFind. [cFileName(MAX_PATH*2-10), cAlternateFileName(14*2-10)]

And when I decrease another 10 bytes from each array, the function runs smoothly again. [cFileName(MAX_PATH*2-20), cAlternateFileName(14*2-20)]

What is going on here

Hoe should I define WIN32_FIND_DATA ?


Code:
Option Explicit

Public Const INVALID_HANDLE_VALUE As Long = -1
Public Const MAX_PATH As Long = 260

Public Enum FileAttributes
FILE_ATTRIBUTE_READONLY = &H1
FILE_ATTRIBUTE_HIDDEN = &H2
FILE_ATTRIBUTE_SYSTEM = &H4
FILE_ATTRIBUTE_DIRECTORY = &H10
FILE_ATTRIBUTE_ARCHIVE = &H20
FILE_ATTRIBUTE_DEVICE = &H40
FILE_ATTRIBUTE_NORMAL = &H80
FILE_ATTRIBUTE_TEMPORARY = &H100
FILE_ATTRIBUTE_SPARSE_FILE = &H200
FILE_ATTRIBUTE_REPARSE_POINT = &H400
FILE_ATTRIBUTE_COMPRESSED = &H800
FILE_ATTRIBUTE_OFFLINE = &H1000
FILE_ATTRIBUTE_NOT_CONTENT_INDEXED = &H2000
FILE_ATTRIBUTE_ENCRYPTED = &H4000
FILE_ATTRIBUTE_VIRTUAL = &H10000
End Enum

Public Type FILETIME
dwLowDateTime As Long
dwHighDateTime As Long
End Type
Public Type WIN32_FIND_DATA
dwFileAttributes As FileAttributes
ftCreationTime As FILETIME
ftLastAccessTime As FILETIME
ftLastWriteTime As FILETIME
nFileSizeHigh As Long
nFileSizeLow As Long
dwReserved0 As Long
dwReserved1 As Long
cFileName(MAX_PATH) As Byte
cAlternateFileName(14) As Byte
End Type

Public Declare Function FindClose Lib "kernel32" ( _
ByVal hFindFile As Long _
) As Boolean
Public Declare Function FindFirstFile Lib "kernel32" Alias "FindFirstFileW" ( _
lpFileName As Any, _
lpFindFileData As WIN32_FIND_DATA _
) As Long
Public Declare Function FindNextFile Lib "kernel32" Alias "FindNextFileW" ( _
ByVal hFindFile As Long, _
lpFindFileData As WIN32_FIND_DATA _
) As Boolean
Public Declare Function GetLastError Lib "kernel32" ( _
) As Long

Sub Main()
EnumFilesFind "C:*"
End Sub
Sub EnumFilesFind(sPath As String)
Dim FindData As WIN32_FIND_DATA
Dim hFind As Long
Dim sName As String
Dim bClose As Boolean
hFind = FindFirstFile(ByVal StrPtr(sPath), FindData)
If hFind = INVALID_HANDLE_VALUE Then
Debug.Print "Error: "; GetLastError()
Else
Do: sName = Left$(FindData.cFileName, InStr(FindData.cFileName, vbNullChar) - 1)
Debug.Print sName
Loop While FindNextFile(hFind, FindData)
bClose = FindClose(hFind)
Debug.Print bClose
End If
End Sub

Copyright 2005-08 www.BigResource.com, All rights reserved