nzfire
asked on
List files and folders vb.net
Hi All,
I need to specify a folder and loop through all the subfolders and files in those and list them.
I am using vb/net (2005).
I need to specify a folder and loop through all the subfolders and files in those and list them.
I am using vb/net (2005).
i am writing the code for reading folders , subfolders and subfiles of a given folder and i am writing all those folders,subfolders list in a text file. try this
Imports System.IO
Public Class Form1
Dim dirpath As String
Function GetFolderSize(ByVal dPath As String, ByVal includeSubFolders As Boolean) As Long
Dim files() As String
files = System.IO.Directory.GetFil es("f:\gop i", "*.*", IO.SearchOption.AllDirecto ries)
Dim objAssembly As Reflection.Assembly = Reflection.Assembly.GetAss embly(Me.G etType)
Dim strAppPath As String = objAssembly.CodeBase
strAppPath = strAppPath.Replace("Window sApplicati on3.dll", "")
Dim objUri As Uri = New Uri(strAppPath)
strAppPath = Application.StartupPath 'objUri.AbsolutePath
Dim strBatchFilePath As String = strAppPath + "\folders.txt"
Dim sw As StreamWriter = Nothing
sw = File.CreateText(strBatchFi lePath)
Dim ReadString As String = "@echo off"
sw.WriteLine(ReadString)
For Each fname As String In files
' Console.WriteLine(fname)
sw.WriteLine(fname)
Next
End Function
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
GetFolderSize("f:\gopi", True)
End Sub
End Class
if you want to show these folders, sub folders in a treeview let me know....
Imports System.IO
Public Class Form1
Dim dirpath As String
Function GetFolderSize(ByVal dPath As String, ByVal includeSubFolders As Boolean) As Long
Dim files() As String
files = System.IO.Directory.GetFil
Dim objAssembly As Reflection.Assembly = Reflection.Assembly.GetAss
Dim strAppPath As String = objAssembly.CodeBase
strAppPath = strAppPath.Replace("Window
Dim objUri As Uri = New Uri(strAppPath)
strAppPath = Application.StartupPath 'objUri.AbsolutePath
Dim strBatchFilePath As String = strAppPath + "\folders.txt"
Dim sw As StreamWriter = Nothing
sw = File.CreateText(strBatchFi
Dim ReadString As String = "@echo off"
sw.WriteLine(ReadString)
For Each fname As String In files
' Console.WriteLine(fname)
sw.WriteLine(fname)
Next
End Function
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
GetFolderSize("f:\gopi", True)
End Sub
End Class
if you want to show these folders, sub folders in a treeview let me know....
Hi nzfire;
Here is a solution using the new worker thread in .Net 2005. If you do not want to use a new thread then the code in BgWorker_DoWork and SearchFiles is the code to do what you want.
This code sample assumes that the form has the following controls on it:
TextBox called txtSearchPath
TextBox called txtSearchPattern
Label called lblMessage
Button called btnStart
ListBox called lstFiles
Imports System.IO
Public Class SearchFilesFrm
' To set up for a background operation, add an event handler for the DoWork event.
' Call your time-consuming operation in this event handler. To start the operation,
' call RunWorkerAsync. To receive notifications of progress updates, handle the
' ProgressChanged event. To receive a notification when the operation is completed,
' handle the RunWorkerCompleted event.
' Note
' You must be careful not to manipulate any user-interface objects in your DoWork
' event handler. Instead, communicate to the user interface through the
' ProgressChanged and RunWorkerCompleted events.
' If your background operation requires a parameter, call RunWorkerAsync with your
' parameter. Inside the DoWork event handler, you can extract the parameter from
' the DoWorkEventArgs.Argument property.
' Store the results of the search
Private Files As List(Of String)
' Used to prevent nested calls to ProgressChanged
Private CallInProgress As Boolean
' The Worker thread
Private WithEvents BgWorker As New System.ComponentModel.Back groundWork er
Private Sub SearchFilesFrm_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load
' Enable ProgressChanged and Cancellation mothed
BgWorker.WorkerReportsProg ress = True
BgWorker.WorkerSupportsCan cellation = True
End Sub
' Start and Stop the search
Private Sub btnStart_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnStart.Click
If btnStart.Text = "Start" Then
If Not Directory.Exists(txtSearch Path.Text. Trim()) Then
MessageBox.Show("The Search Directory does not exist", _
"Path Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Return
End If
If txtSearchPattern.Text.Trim () = "" Then txtSearchPattern.Text = "*"
Dim arguments() As String = {txtSearchPath.Text.Trim() , _
txtSearchPattern.Text.Trim ()}
lstFiles.Items.Clear()
' Start the background worker thread. Thread runs in DoWork event.
BgWorker.RunWorkerAsync(ar guments)
btnStart.Text = "Stop"
Else
BgWorker.CancelAsync()
End If
End Sub
' Start the Asynchronous file search. The background thread does it work from
' this event.
Private Sub BgWorker_DoWork(ByVal sender As Object, _
ByVal e As System.ComponentModel.DoWo rkEventArg s) Handles BgWorker.DoWork
'Retrieve the search path which was requested
Dim path As String = DirectCast(e.Argument, String())(0)
Dim pattern As String = DirectCast(e.Argument, String())(1)
' Invoke the worker procedure
Files = New List(Of String)
SearchFiles(path, pattern)
' Return a result to the RunWorkerCompleted event
Dim message As String = String.Format("Found {0} Files", Files.Count)
e.Result = message
End Sub
' Recursively search directory and sub directories
Private Sub SearchFiles(ByVal path As String, ByVal pattern As String)
' Displat message
Dim message As String = String.Format("Parsing Directory {0}", path)
BgWorker.ReportProgress(0, message)
'Read the files and if the Stop button is pressed cancel the operation
For Each fileName As String In Directory.GetFiles(path, pattern)
If BgWorker.CancellationPendi ng Then Return
Files.Add(fileName)
Next
For Each dirName As String In Directory.GetDirectories(p ath)
If BgWorker.CancellationPendi ng Then Return
SearchFiles(dirName, pattern)
Next
End Sub
' The bacground thread calls this event when you make a call to ReportProgress
' It is OK to access user controls in the UI from this event.
' If you use a Progress Bar or some other control to report the tasks progress
' you should avoid unnecessary calls to ReportProgress method because this causes
' a thread switch which is a relatively expensive in terms of processing time.
Private Sub BgWorker_ProgressChanged(B yVal sender As Object, _
ByVal e As System.ComponentModel.Prog ressChange dEventArgs ) _
Handles BgWorker.ProgressChanged
' Reject a nested call.
If CallInProgress Then Return
CallInProgress = True
' Display the message received in the UserState property
lblMessage.Text = e.UserState.ToString()
' Display all files added since last call.
For idx As Integer = lstFiles.Items.Count To Files.Count - 1
lstFiles.Items.Add(Files(i dx))
Next
' If a Me.Refresh is in this code you will need to place a Application.DoEvents()
' otherwise the UI will not respond without them it works fine.
' Me.Refresh()
' Let the Windows OS process messages in the queue
' Application.DoEvents()
CallInProgress = False
End Sub
' The background thread calls this event just before it reaches the End Sub
' of the DoWork event. It is OK to access user controls in the UI from this event.
Private Sub BgWorker_RunWorkerComplete d(ByVal sender As Object, _
ByVal e As System.ComponentModel.RunW orkerCompl etedEventA rgs) _
Handles BgWorker.RunWorkerComplete d
' Display the last message and reset the Start/Stop button text
lblMessage.Text = e.Result.ToString()
btnStart.Text = "Start"
End Sub
End Class
Fernando
Here is a solution using the new worker thread in .Net 2005. If you do not want to use a new thread then the code in BgWorker_DoWork and SearchFiles is the code to do what you want.
This code sample assumes that the form has the following controls on it:
TextBox called txtSearchPath
TextBox called txtSearchPattern
Label called lblMessage
Button called btnStart
ListBox called lstFiles
Imports System.IO
Public Class SearchFilesFrm
' To set up for a background operation, add an event handler for the DoWork event.
' Call your time-consuming operation in this event handler. To start the operation,
' call RunWorkerAsync. To receive notifications of progress updates, handle the
' ProgressChanged event. To receive a notification when the operation is completed,
' handle the RunWorkerCompleted event.
' Note
' You must be careful not to manipulate any user-interface objects in your DoWork
' event handler. Instead, communicate to the user interface through the
' ProgressChanged and RunWorkerCompleted events.
' If your background operation requires a parameter, call RunWorkerAsync with your
' parameter. Inside the DoWork event handler, you can extract the parameter from
' the DoWorkEventArgs.Argument property.
' Store the results of the search
Private Files As List(Of String)
' Used to prevent nested calls to ProgressChanged
Private CallInProgress As Boolean
' The Worker thread
Private WithEvents BgWorker As New System.ComponentModel.Back
Private Sub SearchFilesFrm_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.Load
' Enable ProgressChanged and Cancellation mothed
BgWorker.WorkerReportsProg
BgWorker.WorkerSupportsCan
End Sub
' Start and Stop the search
Private Sub btnStart_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnStart.Click
If btnStart.Text = "Start" Then
If Not Directory.Exists(txtSearch
MessageBox.Show("The Search Directory does not exist", _
"Path Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Return
End If
If txtSearchPattern.Text.Trim
Dim arguments() As String = {txtSearchPath.Text.Trim()
txtSearchPattern.Text.Trim
lstFiles.Items.Clear()
' Start the background worker thread. Thread runs in DoWork event.
BgWorker.RunWorkerAsync(ar
btnStart.Text = "Stop"
Else
BgWorker.CancelAsync()
End If
End Sub
' Start the Asynchronous file search. The background thread does it work from
' this event.
Private Sub BgWorker_DoWork(ByVal sender As Object, _
ByVal e As System.ComponentModel.DoWo
'Retrieve the search path which was requested
Dim path As String = DirectCast(e.Argument, String())(0)
Dim pattern As String = DirectCast(e.Argument, String())(1)
' Invoke the worker procedure
Files = New List(Of String)
SearchFiles(path, pattern)
' Return a result to the RunWorkerCompleted event
Dim message As String = String.Format("Found {0} Files", Files.Count)
e.Result = message
End Sub
' Recursively search directory and sub directories
Private Sub SearchFiles(ByVal path As String, ByVal pattern As String)
' Displat message
Dim message As String = String.Format("Parsing Directory {0}", path)
BgWorker.ReportProgress(0,
'Read the files and if the Stop button is pressed cancel the operation
For Each fileName As String In Directory.GetFiles(path, pattern)
If BgWorker.CancellationPendi
Files.Add(fileName)
Next
For Each dirName As String In Directory.GetDirectories(p
If BgWorker.CancellationPendi
SearchFiles(dirName, pattern)
Next
End Sub
' The bacground thread calls this event when you make a call to ReportProgress
' It is OK to access user controls in the UI from this event.
' If you use a Progress Bar or some other control to report the tasks progress
' you should avoid unnecessary calls to ReportProgress method because this causes
' a thread switch which is a relatively expensive in terms of processing time.
Private Sub BgWorker_ProgressChanged(B
ByVal e As System.ComponentModel.Prog
Handles BgWorker.ProgressChanged
' Reject a nested call.
If CallInProgress Then Return
CallInProgress = True
' Display the message received in the UserState property
lblMessage.Text = e.UserState.ToString()
' Display all files added since last call.
For idx As Integer = lstFiles.Items.Count To Files.Count - 1
lstFiles.Items.Add(Files(i
Next
' If a Me.Refresh is in this code you will need to place a Application.DoEvents()
' otherwise the UI will not respond without them it works fine.
' Me.Refresh()
' Let the Windows OS process messages in the queue
' Application.DoEvents()
CallInProgress = False
End Sub
' The background thread calls this event just before it reaches the End Sub
' of the DoWork event. It is OK to access user controls in the UI from this event.
Private Sub BgWorker_RunWorkerComplete
ByVal e As System.ComponentModel.RunW
Handles BgWorker.RunWorkerComplete
' Display the last message and reset the Start/Stop button text
lblMessage.Text = e.Result.ToString()
btnStart.Text = "Start"
End Sub
End Class
Fernando
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Great, thanks.
That was the simplest bit of code, and it works just fine.
Thanks to the others that posted code...
That was the simplest bit of code, and it works just fine.
Thanks to the others that posted code...
Great code Fernando. I'd like to utilize a similar logic for something I'm trying out...if you're interested, my new question is at https://www.experts-exchange.com/questions/23260962/background-scanning.html
Thanx!
Thanx!
Dim files() As String
files = System.IO.Directory.GetFil
For Each fname As String In files
Console.WriteLine(fname)
Next