Monday, December 10, 2012

Retrieve all the files in a folder and their subfolders using VBScript or C#

To get all the files in folders and their subfolders of a given directory in an hirarchial format into a text file

' VBScript

1. Create a .txt file and paste the below vbscript code into that and save the file with .VBS extension.
2. Change the source folder path and destination path.
3. Then double click on the .vbs file, it will take few seconds and generate a text file with the details on the given path.

Dim oFSO, oFldr

set oFSO = CreateObject("Scripting.FileSystemObject")
Call Folders()

Function Folders()
set oFldr = oFSO.GetFolder("D:\Projects")
call GetSubFolders()
End Function

Function GetSubFolders()
for each files1 in oFldr.Files
call WriteFile(oFldr.Path & " " & files1.name)
Next
for each subFldr in oFldr.SubFolders
for each oFldr in subFldr.SubFolders
Call GetSubFolders()
next
for each files in subFldr.Files
call WriteFile(subFldr.Path & " " & files.name)
Next
next
End Function
'This works for both .txt & .xls. To use it for xls, just change the extension below to .xls.
Function WriteFile(strFiles)
if not oFSO.FileExists("D:\Projects\FilesIndex.txt") then
set f = oFSO.CreateTextFile("D:\Projects\FilesIndex.txt",1)
Else
set f = oFSO.OpenTextFile("D:\Projects\FilesIndex.txt", 8)
End if
f.WriteLine(strFiles)
f.close()
End Function


' In C# code for the same..
    'private void Folders()
    '   {
    '       DirectoryInfo dir = new DirectoryInfo("D:\\SiteMaker\\Root\\");
    '       //DirectoryInfo dir = new DirectoryInfo("D:\\SiteMaker\\images");
    '       GetSubFolder(dir);
    '   }

    '   private void GetSubFolder(DirectoryInfo dir)
    '   {
    '       foreach (FileInfo files1 in dir.GetFiles())
    '       {
    '           strFiles.Add(files1.FullName);
    '       }
    '       foreach (DirectoryInfo subDir in dir.GetDirectories())
    '       {
    '           foreach (DirectoryInfo dir1 in subDir.GetDirectories())
    '           {
    '               GetSubFolder(dir1);
    '           }
    '           foreach (FileInfo files in subDir.GetFiles())
    '           {
    '               strFiles.Add(files.FullName);
    '           }
    '       }
    '   }

No comments:

Post a Comment