Tag Archives: Diretório

VBA – How to get a of list files inside a folder

And here is one more hint for your VBA toolbox! The macro below returns an array of strings with the list of files which are contained in a previously informed folder:

Public Function ListaArquivos(ByVal Caminho As String) As String()
    'Atenção: Faça referência à biblioteca Micrsoft Scripting Runtime
    Dim FSO As New FileSystemObject
    Dim result() As String
    Dim Pasta As Folder
    Dim Arquivo As File
    Dim Indice As Long
 
 
    ReDim result(0) As String
    If FSO.FolderExists(Caminho) Then
        Set Pasta = FSO.GetFolder(Caminho)
 
        For Each Arquivo In Pasta.Files
            Indice = IIf(result(0) = "", 0, Indice + 1)
            ReDim Preserve result(Indice) As String
            result(Indice) = Arquivo.Name
        Next
    End If
 
    ListaArquivos = result
ErrHandler:
    Set FSO = Nothing
    Set Pasta = Nothing
    Set Arquivo = Nothing
End Function

The macro below is an example of how to call the “ListFiles” Function created before, listing the files inside C:\Temp folder on your computer:

Private Sub ListaArquivos()
    Dim arquivos() As String
    Dim lCtr As Long
    arquivos = ListaArquivos("C:\temp")
    For lCtr = 0 To UBound(arquivos)
      Debug.Print arquivos(lCtr)
    Next
End Sub

Important: As mentioned in the code, you need to add the reference to the Microsoft Scripting Runtime lib to be able to access the File System Objecst (FSO) objecjs.

Enfoy!

.NET : Obter o tamanho de um diretório com o .NET

Dica publicada pelo pessoal da BufaloInfo.

Não há ainda, nas classes do framework, um meio de obter o tamanho total de um diretório. Por isso o tamanho total de um diretório deve ser obtido pela soma do tamanho de seus arquivos e diretórios, da seguinte forma :

public static long Size(System.IO.DirectoryInfo dirInfo)
{
	long total = 0; 
 
	// Obtem o tamanho total dos arquivos no diretório
	foreach(System.IO.FileInfo file in dirInfo.GetFiles())
	total += file.Length; 
 
	// Obtem o tamanho total dos sub-diretórios da pasta
	foreach(System.IO.DirectoryInfo dir in dirInfo.GetDirectories())
	total += Size(dir); 
 
	return total;
}

É interessante observar que esta função é recursiva : Ao encontrar uma pasta a função chama a si mesma para poder calcular o tamanho da pasta e desta forma somar ao tamanho total.

No link abaixo há uma explicação mais detalha sobre Recursividade e os cuidados a considerar em seu uso:

http://pt.wikipedia.org/wiki/Recursividade