USUÁRIO:      SENHA:        SALVAR LOGIN ?    Adicione o VBWEB na sua lista de favoritos   Fale conosco 

 

  Fórum

  Visual Basic
Voltar
Autor Assunto:  verificar existencia de diretório...
Elieser Topassi
Pontos: 2843 Pontos: 2843
SÃO JOSÉ DO RIO PRETO
SP - BRASIL
Postada em 17/10/2004 16:42 hs            
Olá, galera
 
Estou com dois problemas com diretórios:
 
1) Como verificar se um diretório já existe???
 
2) Como verificar se o diretório tem conteúdo (arquivos ou subdiretórios)???
 
Isso tudo sem usar FSO!!!
 
Agradeço a Ajuda


Elieser Carlos Topassi
Analista de Sistemas - Desenvolvedor VB/ASP/.Net

e-mail/msn:
elieser_topassi@yahoo.com.br
São José do Rio Preto,SP - Brasil
_____________________________________________________
Emoções "O caminho do tolo aos seus prórios olhos lhe parece reto, mas o sábio ouve conselhos" (Pv 12:15)

     
Geronimo
Pontos: 2843
JOINVILLE
SC - BRASIL
ENUNCIADA !
Postada em 17/10/2004 16:52 hs            
Esta classe usa API para localizar arquivos com ou sem 'wildcards' e os retorna num array. É bastante rápida e conta com eventos para ajudar a dar um feedback ao usuário do estado da procura.

Para testar crie um form e um class module e renomeie o class module cFindFile. No form crie um commandbutton, um listbox e 2 textboxes (Text1 é para a pasta inicial e text2 para o arquivo a ser achado)

Cole no class module

Option Explicit
'Class Written By:  GDuncan
'              On:  8/11/98
Private Declare Function FindMinFile Lib "kernel32" Alias "FindMinFileA" (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 FindClose Lib "kernel32" (ByVal hFindFile As Long) As Long

Private Const MaxLFNPath = 260

Private Const INVALID_HANDLE_VALUE = -1
Private Const vbBackslash = ""
Private Const vbAllFiles = "*.*"
Private Const vbKeyDot = 46
Private Type FILETIME
  dwLowDateTime As Long
  dwHighDateTime As Long
End Type

Private Type WIN32_FIND_DATA
  dwFileAttributes As Long
  ftCreationTime As FILETIME
  ftMaxAccessTime As FILETIME
  ftMaxWriteTime As FILETIME
  nFileSizeHigh As Long
  nFileSizeLow As Long
  dwReserved0 As Long
  dwReserved1 As Long
  cFileName As String * MaxLFNPath
  cShortFileName As String * 14
End Type

Private WFD As WIN32_FIND_DATA
Private hItem&
Private hFile&
Private msFileSpec        As String
Private msPath            As String
Private mbSearching       As Boolean
Private mbRecursive       As Boolean
Private mlRecursiveLevels As Long
Private mbUseFileSpec     As Boolean
Private mlTotalDirs       As Long
Private mlTotalFiles      As Long

Public Event BeginFindFiles()
Public Event EndFindFiles(FileCount As Long)
Public Event FoundFile(FileName As String, Cancel As Boolean)

Public Property Let Path(ByVal vData As String)
    msPath = vData
End Property

Public Property Get Path() As String
  Path = msPath
End Property

Public Property Let FileSpec(ByVal vData As String)
  msFileSpec = vData
End Property

Public Property Get FileSpec() As String
  FileSpec = msFileSpec
End Property

Private Property Let Searching(ByVal vData As Boolean)
    mbSearching = vData
End Property

Public Property Get Searching() As Boolean
    Searching = mbSearching
End Property

Public Function FindAll(FileListArray As Variant) As Boolean

  Dim asfiles() As String
  ReDim asfiles(0)
  On Error GoTo eop_error
  
  If FindFiles(asfiles()) Then
    FileListArray = asfiles()
    FindAll = True
  Else
    FindAll = False
  End If

eop_error:
  Select Case Err.Number
    Case Is > 0
      FindAll = False
      Err.Raise Err.Number, Err.Source, Err.Description, Err.HelpFile, Err.HelpContext
  End Select
eop_exit:

End Function

Private Property Let Recursive(ByVal vData As Boolean)
  'Future Property
  mbRecursive = vData
End Property

Private Property Get Recursive() As Boolean
  'Future Property
  FileSpec = mbRecursive
End Property

Private Property Let RecursiveLevels(ByVal vData As Long)
  'Future Property
  mlRecursiveLevels = vData
End Property

Private Property Get RecursiveLevels() As Long
  'Future Property
  FileSpec = mlRecursiveLevels
End Property

Private Function FindFiles(asFoundFiles() As String) As Boolean

  ' If we're running & we got a click, it's because DoEvents in
  ' either the SearchDirs() or SearchFileSpec() proc let it happen.
  ' Tell the proc to stop. Once SearchDirs() has un-recursed itself
  ' we'll finish off below where we left off...
  
  Dim drvbitmask&, maxpwr%, pwr%
  FindFiles = False
  If Searching Then
    Searching = False
    GoTo eop_exit
  End If
  On Error Resume Next
  
  ' A parsing routine could be implemented here for
  ' multiple file spec searches, i.e. "*.bmp,*.wmf", etc.
  ' See the MS KB article Q130860 for information on how
  ' FindMinFile() does not handle the "?" wildcard char correctly !!
  If Len(FileSpec) = 0 Then GoTo eop_exit
  
  If Len(Path) = 0 Then GoTo eop_exit
  
  mbSearching = True
  mbUseFileSpec = True
  
  RaiseEvent BeginFindFiles
  
  Call SearchDirs(Path, asFoundFiles())
  
  Searching = False
  mbUseFileSpec = False
  
  mlTotalFiles = UBound(asFoundFiles)
  RaiseEvent EndFindFiles(mlTotalFiles)
  
  FindFiles = True
    
eop_exit:
    
End Function

' This is were it all happens...

' You can use the values in returned in the
' WIN32_FIND_DATA structure to virtually obtain any
' information you want for a particular folder or group of files.

' This recursive procedure is similar to the Dir$ function
' example found in the VB3 help file...

Private Sub SearchDirs(CurPath$, asFoundFiles() As String) ' curpath$ is passed w/ trailing ""
  ' These can't be static!!! They must be
  ' re-allocated on each recursive call.
  Dim dirs%, dirbuf$(), i%
  
  ' This proc to be cancelled by the user.
  ' It's not necessary to have this in the loop
  ' below since the loop works so fast...
  DoEvents
  
  If Not Searching Then GoTo eop_exit
  
  ' This loop finds *every* subdir and file in the current dir
  hItem& = FindMinFile(CurPath$ & vbAllFiles, WFD)
  
  If hItem& <> INVALID_HANDLE_VALUE Then
    Do
      ' Tests for subdirs only...
      If (WFD.dwFileAttributes And vbDirectory) Then
          
        ' If not a  "." or ".." DOS subdir...
        If Asc(WFD.cFileName) <> vbKeyDot Then
          ' This is executed in the mnuFindFiles_Click()
          ' call though it isn't used...
          mlTotalDirs = mlTotalDirs + 1
          ' This is the heart of a recursive proc...
          ' Cache the subdirs of the current dir in the 1 based array.
          ' This proc calls itself below for each subdir cached in the array.
          ' (re-allocating the array only once every 10 itinerations improves speed)
          If (dirs% Mod 10) = 0 Then ReDim Preserve dirbuf$(dirs% + 10)
          dirs% = dirs% + 1
          dirbuf$(dirs%) = Left$(WFD.cFileName, InStr(WFD.cFileName, vbNullChar) - 1)
        End If
      
        ' File size and attribute tests can be used here, i.e:
        ' ElseIf (WFD.dwFileAttributes And vbHidden) = False Then  'etc...
        
        ' Get a total file count for mnuFolderInfo_Click()
      ElseIf Not mbUseFileSpec Then
        mlTotalFiles = mlTotalFiles + 1
      End If
    
    ' Get the next subdir or file
    Loop While FindNextFile(hItem&, WFD)
        
    ' Close the search handle
    Call FindClose(hItem&)
  
  End If
  ' When UseFileSpec% is set mnuFindFiles_Click(),
  ' SearchFileSpec() is called & each folder must be
  ' searched a second time.
  If mbUseFileSpec Then
    Call SearchFileSpec(CurPath$, asFoundFiles())
  End If

  ' Recursively call this proc & iterate through each subdir cached above.
  For i% = 1 To dirs%
    SearchDirs CurPath$ & dirbuf$(i%) & vbBackslash, asFoundFiles()
  Next i%
eop_exit:

End Sub

Private Sub SearchFileSpec(CurPath$, asFoundFiles() As String)
  'curpath$ is passed w/ trailing ""
  ' This procedure *only*  finds files in the
  ' current folder that match the FileSpec$
  Dim Cancel As Boolean
  Dim sTempFile As String
  hFile& = FindMinFile(CurPath$ & FileSpec, WFD)
  If hFile& <> INVALID_HANDLE_VALUE Then
        
    Do
      ' Use DoEvents here since we're loading a ListBox and
      ' there could be hundreds of files matching the FileSpec$
      DoEvents
      If Not mbSearching Then GoTo eop_exit
      
      ReDim Preserve asFoundFiles(UBound(asFoundFiles) + 1)
      sTempFile = CurPath$ & Left$(WFD.cFileName, InStr(WFD.cFileName, vbNullChar) - 1)
      asFoundFiles(UBound(asFoundFiles)) = sTempFile
      
      Cancel = False
      RaiseEvent FoundFile(sTempFile, Cancel)
      mbSearching = Not Cancel
          
      ' Get the next file matching the FileSpec$
    Loop While FindNextFile(hFile&, WFD)
    ' Close the search handle
    Call FindClose(hFile&)
  End If

eop_exit:

End Sub


Cole no form

Dim WithEvents clsFind As CFindFile

Private Sub command1_click()

  Dim asfiles As Variant
  Dim lLoop As Long
  Dim lCount As Long
  Dim bResult As Boolean

  Set clsFind = New CFindFile

  clsFind.Path = Text1          'UNC Paths are supported
  clsFind.FileSpec = Text2    'Wild Cards are also supported

  bResult = clsFind.FindAll(asfiles)

  If VarType(asfiles) = (vbArray + vbString) Then
    lCount = UBound(asfiles)
    For lLoop = 0 To lCount
      List1.AddItem asfiles(lLoop)
    Next lLoop
  End If
End Sub

Private Sub clsFind_BeginFindFiles()
  Me.Caption = "Começando"
End Sub

Private Sub clsFind_EndFindFiles(FileCount As Long)
  Me.Caption = "Achados " & CStr(FileCount) & " Arquivos"
End Sub

Private Sub clsFind_FoundFile(FileName As String, Cancel As Boolean)
  Me.Caption = "Achado: " & FileName
  
End Sub


fonte http://www.codex.com.br/colaboracao/VerOK.asp?ID=566

"O pior inimigo que você poderá encontrar será sempre você mesmo."
   
Msmarcus_RJ
RIO DE JANEIRO
RJ - BRASIL
Postada em 19/10/2004 17:38 hs         
Oi, experiemente usar este metodo aqui, ele é menor!

Bom, em seu projeto faça o seguinte:

Adicione 1 COMMANDBUTTON, 1 TEXTBOX, 3 LABEL, 2 TIMER, 1 FILELISTBOX, e 1 DIRLISTBOX.

Adicione este código abaixo em seu projeto!

Private Sub Command1_Click()
On Error GoTo erros
Dir1.Path = Text1.Text
Label1.Caption = "Diretório encontrado"
Timer1.Enabled = True
Timer1.Interval = 1
Exit Sub
erros:
Label1.Caption = "O diretório não existe"
Timer1.Enabled = True
Timer1.Interval = 1
End Sub
Private Sub Form_Load()
Dir1.Visible = False
File1.Visible = False
End Sub
Private Sub Timer1_Timer()
Dim St
Timer1.Enabled = False
File1.filename = Dir1.Path
St = File1.List(0)
If Trim(St) = "" Then
Label2.Caption = "Nenhum arquivo encontrado"
Timer2.Enabled = True
Timer2.Interval = 1
Else
Label2.Caption = "Arquivo encontrado"
Timer2.Enabled = True
Timer2.Interval = 1
End If
End Sub
Private Sub Timer2_Timer()
Timer2.Enabled = False
Dim Dir2
Dir2 = Dir1.List(0)
If Trim(Dir2) = "" Then
Label3.Caption = "Nenhum Sub-diretório encontrado"
Else
Label3.Caption = "Sub-diretório encontrado"
End If
End Sub
Quando iniciar o projeto, coloque o 'Caminho de um diretório' no TEXTBOX1
E clique no COMMANDBUTTON, ele irá te exibir se o diretório existe, e se existe arquivos e sub-diretórios na PASTA!

O que achou ?

Até mais,

Atenciosamente,
Marcus Vinícius

Se quiser entrar em contato comigo me envie um e-mail para Msmarcus@hotmail.com
Que em breve estarei entrando em contato contigo.
 

______________________________
Resolveu ? Tópico Trancado!

     
Elieser Topassi
Pontos: 2843 Pontos: 2843
SÃO JOSÉ DO RIO PRETO
SP - BRASIL
ENUNCIADA !
Postada em 19/10/2004 17:50 hs            
Obrigado, galera
 
Vou dar uma lida com mais calma em ambos os codigos...
 
depois dou um retorno...


Elieser Carlos Topassi
Analista de Sistemas - Desenvolvedor VB/ASP/.Net

e-mail/msn:
elieser_topassi@yahoo.com.br
São José do Rio Preto,SP - Brasil
_____________________________________________________
Emoções "O caminho do tolo aos seus prórios olhos lhe parece reto, mas o sábio ouve conselhos" (Pv 12:15)

   
Página(s): 1/1    

CyberWEB Network Ltda.    © Copyright 2000-2025   -   Todos os direitos reservados.
Powered by HostingZone - A melhor hospedagem para seu site
Topo da página