Visual Basic, .NET, ASP, VBScript
 

   
   
     

Форум - Общий форум

Страница: 1 |

 

  Вопрос: FindFirstFile и FindNextFile Добавлено: 21.12.02 13:57  

Автор вопроса:  Silent_Sky | ICQ: 134433 

Народ надо получить имена всех файлов в директории. Можно конечно использовать Microsoft Scripting Runtime но я не хочу таскать эту длл с собой... Я так думаю мне могут помочь эти АПИ - функции: FindFirstFile и FindNextFile

Кто нить может мне пример показать с их использованием?

Ответить

  Ответы Всего ответов: 8  

Номер ответа: 1
Автор ответа:
 Иван



Администратор

ICQ: 147688925 

Вопросов: 24
Ответов: 708
 Web-сайт: www.vbnet.ru
 Профиль | | #1
Добавлено: 21.12.02 15:06
Ты зайди в раздел Примеры и там есть примеры их использования в подразделе Файловая система.

Ответить

Номер ответа: 2
Автор ответа:
 Silent_Sky



ICQ: 134433 

Вопросов: 25
Ответов: 44
 Профиль | | #2 Добавлено: 23.12.02 09:40

Но там только:

Дата: 25 июля 2002 г. | Автор: Яковлев Антон | Загрузок: 344

Search (3 Kb) Пример поиска файлов с помощью DirListBox и FileListBox. Все очень просто, но для начинающих самое то, что надо.

 

а мне надо с помощью АПИ- функций...

Ответить

Номер ответа: 3
Автор ответа:
 CyRax



Разработчик Offline Client

ICQ: 204447456 

Вопросов: 180
Ответов: 4229
 Web-сайт: basicproduction.nm.ru
 Профиль | | #3
Добавлено: 23.12.02 22:05

Насчёт АПИ не знаю.

В VB есть функция DIR

Syntax

Dir[(pathname[, attributes])]

The Dir function syntax has these parts:

Part ;Description
pathname Optional. String expression that specifies a file name—may include directory or folder, and drive. A zero-length string ("") is returned if pathname is not found.
attributes Optional. Constant or numeric expression, whose sum specifies file attributes. If omitted, all files are returned that match pathname.
Settings

The attributes argument settings are:

Constant Value ;Description
 
vbNormal 0 Normal
vbHidden 2 Hidden
vbSystem 4 System file
vbVolume 8 Volume label; if specified, all other attributes are ignored
vbDirectory 16 ;Directory or folder

Ответить

Номер ответа: 4
Автор ответа:
 kvakak



Вопросов: 0
Ответов: 7
 Профиль | | #4 Добавлено: 24.12.02 11:15

Есть такой сайт  http://www.allapi.net. На нём есть два справочника: API-Guide 3.7 (925 API`шных фунций с описаниями и примерами использования) и ApiViewer (описания констант - 55634 штук, фунций   - 4813 штук, подпр.    - 1708 штук, типов     - 457 штук). Ниже пример для FindFirstFile ... из первого справочника. У себя проверил, работает. Правда не так, чтобы очень быстро.

=============================================

'Create a form with a command button (command1), a list box (list1)
'and four text boxes (text1, text2, text3 and text4).
'Type in the first textbox a startingpath like c:\
'and in the second textbox you put a pattern like *.* or *.txt

Private Declare Function FindFirstFile Lib "kernel32" Alias "FindFirstFileA" (ByVal lpFileName As String, lpFindFileData As WIN32_FIND_DATA) As Long
Private Declare Function FindNextFile Lib "kernel32" Alias "FindNextFileA" (ByVal hFindFile As Long, lpFindFileData As WIN32_FIND_DATA) As Long
Private Declare Function GetFileAttributes Lib "kernel32" Alias "GetFileAttributesA" (ByVal lpFileName As String) As Long
Private Declare Function FindClose Lib "kernel32" (ByVal hFindFile As Long) As Long

Const MAX_PATH = 260
Const MAXDWORD = &HFFFF
Const INVALID_HANDLE_VALUE = -1
Const FILE_ATTRIBUTE_ARCHIVE = &H20
Const FILE_ATTRIBUTE_DIRECTORY = &H10
Const FILE_ATTRIBUTE_HIDDEN = &H2
Const FILE_ATTRIBUTE_NORMAL = &H80
Const FILE_ATTRIBUTE_READONLY = &H1
Const FILE_ATTRIBUTE_SYSTEM = &H4
Const FILE_ATTRIBUTE_TEMPORARY = &H100

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
Function StripNulls(OriginalStr As String) As String
    If (InStr(OriginalStr, Chr(0)) > 0) Then
        OriginalStr = Left(OriginalStr, InStr(OriginalStr, Chr(0)) - 1)
    End If
    StripNulls = OriginalStr
End Function

Function FindFilesAPI(path As String, SearchStr As String, FileCount As Integer, DirCount As Integer)
    'KPD-Team 1999
    'E-Mail: KPDTeam@Allapi.net
    'URL: http://www.allapi.net/

    Dim FileName As String ' Walking filename variable...
    Dim DirName As String ' SubDirectory Name
    Dim dirNames() As String ' Buffer for directory name entries
    Dim nDir As Integer ' Number of directories in this path
    Dim i As Integer ' For-loop counter...
    Dim hSearch As Long ' Search Handle
    Dim WFD As WIN32_FIND_DATA
    Dim Cont As Integer
    If Right(path, 1) <> "\" Then path = path & "\"
    ' Search for subdirectories.
    nDir = 0
    ReDim dirNames(nDir)
    Cont = True
    hSearch = FindFirstFile(path & "*", 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(path & 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
    ' Walk through this directory and sum file sizes.
    hSearch = FindFirstFile(path & SearchStr, WFD)
    Cont = True
    If hSearch <> INVALID_HANDLE_VALUE Then
        While Cont
            FileName = StripNulls(WFD.cFileName)
            If (FileName <> ".") And (FileName <> "..") Then
                FindFilesAPI = FindFilesAPI + (WFD.nFileSizeHigh * MAXDWORD) + WFD.nFileSizeLow
                FileCount = FileCount + 1
                List1.AddItem path & FileName
            End If
            Cont = FindNextFile(hSearch, WFD) ' Get next file
        Wend
        Cont = FindClose(hSearch)
    End If
  

Ответить

Номер ответа: 5
Автор ответа:
 Silent_Sky



ICQ: 134433 

Вопросов: 25
Ответов: 44
 Профиль | | #5 Добавлено: 25.12.02 09:56

Спасибо огромное за пример.

Про сайт этот я знаю, тока не могу никак траффика выбить что бы скачать их себе...

Ответить

Номер ответа: 6
Автор ответа:
 sne



Разработчик Offline Client

ICQ: 233286456 

Вопросов: 34
Ответов: 5445
 Web-сайт: hw.t-k.ru
 Профиль | | #6
Добавлено: 31.12.02 00:50

'Вставь в модуль следующий код:

Option Explicit

Private Declare Function FindFirstFile Lib "kernel32" Alias "FindFirstFileA" (ByVal lpFileName As String, lpFindFileData As WIN32_FIND_DATA) As Long
Private Declare Function FindClose Lib "kernel32" (ByVal hFindFile As Long) As Long
Private Declare Function FindNextFile Lib "kernel32" Alias "FindNextFileA" (ByVal hFindFile As Long, lpFindFileData As WIN32_FIND_DATA) As Long

Public Enum AtributConst
    FILE_ATTRIBUTE_ARCHIVE = &H20
    FILE_ATTRIBUTE_COMPRESSED = &H800
    FILE_ATTRIBUTE_DIRECTORY = &H10
    'FILE_ATTRIBUTE_ENCRYPTED=???
    FILE_ATTRIBUTE_HIDDEN = &H2
    FILE_ATTRIBUTE_NORMAL = &H80
    'FILE_ATTRIBUTE_OFFLINE=???
    FILE_ATTRIBUTE_READONLY = &H1
    'FILE_ATTRIBUTE_REPARSE_POINT=???
    'FILE_ATTRIBUTE_SPARSE_FILE=???
    FILE_ATTRIBUTE_SYSTEM = &H4
    FILE_ATTRIBUTE_TEMPORARY = &H100
End Enum
Public Type FILETIME
    dwLowDateTime       As Long
    dwHighDateTime      As Long
End Type
Public Type WIN32_FIND_DATA
    dwFileAttributes    As AtributConst
    ftCreationTime      As FILETIME
    ftLastAccessTime    As FILETIME
    ftLastWriteTime     As FILETIME
    nFileSizeHigh       As Long
    nFileSizeLow        As Long
    dwReserved0         As Long
    dwReserved1         As Long
    cFileName           As String * 260
    cAlternate          As String * 14
End Type
Private Const INVALID_HANDLE_VALUE = -1                     'Âîçíèêàåò ïðè îòñóòñòâèè ôàéëà

Public Sub StartFind(ByVal sFilter As String, ByRef FindArray() As WIN32_FIND_DATA)
    Dim lngHandle As Long                                       'Õàíäë îòêðûòîãî ôàéëà
    Dim TempData As WIN32_FIND_DATA                             'Âðåìåííàÿ ïåðåìåííàÿ
   
    lngHandle = FindFirstFile(sFilter & vbNullChar, TempData)   'Íàõîäèì õýíäë
    If lngHandle = INVALID_HANDLE_VALUE Then Exit Sub           'Åñëè íè÷åãî íåò, óõîäèì
   
    ReDim FindArray(0)                                          'Ðåñàéçèì ìàññèâ ïîä 1-é ôàéë (äèðåêòîðèþ;)
    FindArray(0) = TempData                                     'Ïðèñâàåâàåì èíôîðìàöèþ î ôàéëå
   
    Do Until FindNextFile(lngHandle, TempData) = 0              'Ïðîäîëæàåì ïîèñê, ïîêà íå îøèáåìñÿ
        DoEvents                                                'Íå çàâèñàåì
        ReDim Preserve FindArray(UBound(FindArray) + 1)         'Ðåñàéçèì ìàññèâ íà 1 áîëüøå ïðåæíåãî
        FindArray(UBound(FindArray)) = TempData                 'Ïðèñâîåíèå î÷åðåäíîé ïîðöèè èíôîðìàöèè
    Loop

    Call FindClose(lngHandle)                                   'Ïîáàëîâàëèñü äà è õâàòèò...
End Sub

Public Sub ScanForFiles(ByVal StartPath As String, Pattern As String, Files() As String)
    Dim i_s As Long, Dir1() As String, File1() As String, File As Long
    File = UboundS(Files()) + 1
    If Not Right$(StartPath, 1) = "\" Then StartPath = StartPath + "\

Ответить

Номер ответа: 7
Автор ответа:
 999



Вопросов: 13
Ответов: 26
 Web-сайт: wolf002.narod.ru
 Профиль | | #7
Добавлено: 06.03.05 00:45
Как переипсать эту функцию на VB.net

['Create a form with a command button (command1), a list box (list1)
'and four text boxes (text1, text2, text3 and text4).
'Type in the first textbox a startingpath like c:\
'and in the second textbox you put a pattern like *.* or *.txt

Private Declare Function FindFirstFile Lib "kernel32" Alias "FindFirstFileA" (ByVal lpFileName As String, lpFindFileData As WIN32_FIND_DATA) As Long
Private Declare Function FindNextFile Lib "kernel32" Alias "FindNextFileA" (ByVal hFindFile As Long, lpFindFileData As WIN32_FIND_DATA) As Long
Private Declare Function GetFileAttributes Lib "kernel32" Alias "GetFileAttributesA" (ByVal lpFileName As String) As Long
Private Declare Function FindClose Lib "kernel32" (ByVal hFindFile As Long) As Long

Const MAX_PATH = 260
Const MAXDWORD = &HFFFF
Const INVALID_HANDLE_VALUE = -1
Const FILE_ATTRIBUTE_ARCHIVE = &H20
Const FILE_ATTRIBUTE_DIRECTORY = &H10
Const FILE_ATTRIBUTE_HIDDEN = &H2
Const FILE_ATTRIBUTE_NORMAL = &H80
Const FILE_ATTRIBUTE_READONLY = &H1
Const FILE_ATTRIBUTE_SYSTEM = &H4
Const FILE_ATTRIBUTE_TEMPORARY = &H100

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
Function StripNulls(OriginalStr As String) As String
    If (InStr(OriginalStr, Chr(0)) > 0) Then
        OriginalStr = Left(OriginalStr, InStr(OriginalStr, Chr(0)) - 1)
    End If
    StripNulls = OriginalStr
End Function

Function FindFilesAPI(path As String, SearchStr As String, FileCount As Integer, DirCount As Integer)
    'KPD-Team 1999
    'E-Mail: KPDTeam@Allapi.net
    'URL: http://www.allapi.net/

    ;Dim FileName As String ' Walking filename variable...
    ;Dim DirName As String ' SubDirectory Name
    ;Dim dirNames() As String ' Buffer for directory name entries
    ;Dim nDir As Integer ' Number of directories in this path
    ;Dim i As Integer ' For-loop counter...
    ;Dim hSearch As Long ' Search Handle
    ;Dim WFD As WIN32_FIND_DATA
    ;Dim Cont As Integer
    If Right(path, 1) <> "\" Then path = path & "\"
    ' Search for subdirectories.
    nDir = 0
    ReDim dirNames(nDir)
    Cont = True
    hSearch = FindFirstFile(path & "*", 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(path & 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
    ' Walk through this directory and sum file sizes.
    hSearch = FindFirstFile(path & SearchStr, WFD)
    Cont = True
    If hSearch <> INVALID_HANDLE_VALUE Then
        While Cont
            FileName = StripNulls(WFD.cFileName)
            If (FileName <> ".";) And (FileName <> "..";) Then
                FindFilesAPI = FindFilesAPI + (WFD.nFileSizeHigh * MAXDWORD) + WFD.nFileSizeLow
                FileCount = FileCount + 1
                List1.AddItem path & FileName
            End If
            Cont = FindNextFile(hSearch, WFD) ' Get next file
        Wend
        Cont = FindClose(hSearch)
    End If

Ответить

Номер ответа: 8
Автор ответа:
 Александр



Разработчик Offline Client

ICQ: 204034 

Вопросов: 106
Ответов: 1919
 Профиль | | #8 Добавлено: 08.03.05 11:52
System.IO.<___>

Ответить

Страница: 1 |

Поиск по форуму



© Copyright 2002-2011 VBNet.RU | Пишите нам