473,666 Members | 2,165 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Loop thru all subfolders and list all files under each

I need a VB routine to loop thru a select top folder to find all subfolders
and list all subfolders/files under each of these subfolders.
Any help is greatly appreciated.
Bill
Nov 21 '05 #1
9 18987
"Bill Nguyen" <bi************ *****@jaco.com> schrieb:
I need a VB routine to loop thru a select top folder to find all subfolders
and list all subfolders/files under each of these subfolders.


<URL:http://dotnet.mvps.org/dotnet/samples/filesystem/FileSystemEnume rator.zip>

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://classicvb.org/petition/>

Nov 21 '05 #2
I appreciated this but I really don't know where to start. The readme.txt
doesn't tell me a thing about how to get this going.
Any thing I have to do in order to get the demo running?

Bill

"Herfried K. Wagner [MVP]" <hi************ ***@gmx.at> wrote in message
news:%2******** *******@TK2MSFT NGP14.phx.gbl.. .
"Bill Nguyen" <bi************ *****@jaco.com> schrieb:
I need a VB routine to loop thru a select top folder to find all
subfolders and list all subfolders/files under each of these subfolders.


<URL:http://dotnet.mvps.org/dotnet/samples/filesystem/FileSystemEnume rator.zip>

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://classicvb.org/petition/>

Nov 21 '05 #3
"Bill Nguyen" <bi************ *****@jaco.com> schrieb:
I appreciated this but I really don't know where to start. The readme.txt
doesn't tell me a thing about how to get this going.
Any thing I have to do in order to get the demo running?


I see, my sample is a bit "oversized" . The listing below shows a reduced
version:

\\\
Imports System.IO

Friend Module Module1
Friend Sub Main()
EnumerateDirect ory("C:\WINDOWS ")
End Sub

Private Sub EnumerateDirect ory(ByVal RootDirectory As String)

For Each s As String In Directory.GetFi les(RootDirecto ry)
Console.WriteLi ne("File found: " & s)
Next s
For Each s As String In Directory.GetDi rectories(RootD irectory)

' Prevent enumeration of reparse points.
'
' Platform SDK: Storage -- Reparse Points
'
<URL:http://msdn.microsoft. com/library/en-us/fileio/base/reparse_points. asp>
'
' You can create an infinitely recursive directory tree
'
<URL:http://blogs.msdn.com/oldnewthing/archive/2004/12/27/332704.aspx>
If _
Not (File.GetAttrib utes(s) And FileAttributes. ReparsePoint)
= _
FileAttributes. ReparsePoint _
Then
Console.WriteLi ne("Directory found: " & s)
EnumerateDirect ory(s)
End If
Next s
End Sub
End Module
///

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://classicvb.org/petition/>

Nov 21 '05 #4
herfried;
I can't run any of your code in your application. It gave me some kind of
error!
Below is my newbie version but all it can do is to list all files in a
single-level directory.
How can I loop thru all directories to list files in lowest level folder and
move to the next?

Thanks a billion

Bill

Private Sub Button1_Click(B yVal sender As System.Object, ByVal e As
System.EventArg s) Handles Button1.Click

Dim mDir, mFile, rootDir, mrootPath, mFolder, mFileName As String

Dim mCount As Integer

rootDir = "C:\windows "

' For Each s As String In Directory.GetFi les(rootDir)

For Each d As String In Directory.GetDi rectories(rootD ir)

'Console.WriteL ine("File found: " & s)

'mSourceFile = .FileName.Subst ring(OpenFileDi alog1.FileName. LastIndexOf("\" )
+ 1)

mFolder = d.Substring(d.L astIndexOf("\") + 1)

mrootPath = d.Substring(0, d.LastIndexOf(" \"))

mDir += mrootPath & "\" & mFolder & vbCrLf

For Each f As String In Directory.GetFi les(d)

mFileName = f.Substring(f.L astIndexOf("\") + 1)

'mrootPath = f.Substring(1, d.LastIndexOf(" \"))

mFile += mFileName & vbCrLf

Next f

MsgBox(mFile)

mFile = ""

Next d

MsgBox(mDir)

End Sub

"Herfried K. Wagner [MVP]" <hi************ ***@gmx.at> wrote in message
news:Oc******** ******@TK2MSFTN GP14.phx.gbl...
"Bill Nguyen" <bi************ *****@jaco.com> schrieb:
I appreciated this but I really don't know where to start. The readme.txt
doesn't tell me a thing about how to get this going.
Any thing I have to do in order to get the demo running?


I see, my sample is a bit "oversized" . The listing below shows a reduced
version:

\\\
Imports System.IO

Friend Module Module1
Friend Sub Main()
EnumerateDirect ory("C:\WINDOWS ")
End Sub

Private Sub EnumerateDirect ory(ByVal RootDirectory As String)

For Each s As String In Directory.GetFi les(RootDirecto ry)
Console.WriteLi ne("File found: " & s)
Next s
For Each s As String In Directory.GetDi rectories(RootD irectory)

' Prevent enumeration of reparse points.
'
' Platform SDK: Storage -- Reparse Points
'
<URL:http://msdn.microsoft. com/library/en-us/fileio/base/reparse_points. asp>
'
' You can create an infinitely recursive directory tree
'
<URL:http://blogs.msdn.com/oldnewthing/archive/2004/12/27/332704.aspx>
If _
Not (File.GetAttrib utes(s) And FileAttributes. ReparsePoint)
= _
FileAttributes. ReparsePoint _
Then
Console.WriteLi ne("Directory found: " & s)
EnumerateDirect ory(s)
End If
Next s
End Sub
End Module
///

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://classicvb.org/petition/>

Nov 21 '05 #5
"Bill Nguyen" <bi************ *****@jaco.com> schrieb:
I can't run any of your code in your application. It gave me some kind of
error!


Error message?

--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://classicvb.org/petition/>

Nov 21 '05 #6
The whole purpose of Herfried's method was that it is a *recursive*
method, i. e. it calls itself. But you have removed the recursion and
therefore it only scans the first directory.

Here is Herfried's method again (slightly altered):

Imports System.IO

Friend Module Module1
Friend Sub Main()
EnumerateDirect ory("C:\WINDOWS ")
End Sub

Private Sub EnumerateDirect ory(ByVal RootDirectory As String)

For Each s As String In Directory.GetFi les(RootDirecto ry)
'******* Perform task on file s here. Replace with your
own file
'******* manipulation code here
Next

For Each s As String In Directory.GetDi rectories(RootD irectory)

'Correct me if I'm wrong Herfried but this line prevents
recursion into
'empty folders
If Not (File.GetAttrib utes(s) And
FileAttributes. ReparsePoint) = _
FileAttributes. ReparsePoint Then

'***** Perform work in folder s here. Replace with
your
'***** folder manipuation code here

'Notice we're calling ourself here to get data on child
folders
'This is the recursive part!
EnumerateDirect ory(s)
End If
Next
End Sub
End Module
BTW: Why are you using substring parse out the portions of your
folders and filename? why not use the methods in the System.IO
namespace?

For example, instead of:

mrootPath = d.Substring(0, d.LastIndexOf(" \"))

use this instead:

mrootPath = Path.GetPathRoo t(d)

and instead of

mFileName = f.Substring(f.L astIndexOf("\") + 1)

use this instead:

mFileName = Path.GetFileNam e(f)

Nov 21 '05 #7
Chris;

Thanks for the tip.
mFileName = Path.GetFileNam e(f) worked great!

mrootPath = Path.GetPathRoo t(d) only give me the root path. I need to get
the name of the folder at subsequent levels.
For example, the full path:

C:\Base\Level1\ level2\level3\L evel4\Filename. TXT
C:\Base is the base (root) dir.
I need to parse the folder name Level1 thru level4 and assign a
corresponding folder level ID 2,3,4) to these folders.

Any idea how to do this?
Thanks in advance.

Bill


"Chris Dunaway" <du******@gmail .com> wrote in message
news:11******** *************@z 14g2000cwz.goog legroups.com...
The whole purpose of Herfried's method was that it is a *recursive*
method, i. e. it calls itself. But you have removed the recursion and
therefore it only scans the first directory.

Here is Herfried's method again (slightly altered):

Imports System.IO

Friend Module Module1
Friend Sub Main()
EnumerateDirect ory("C:\WINDOWS ")
End Sub

Private Sub EnumerateDirect ory(ByVal RootDirectory As String)

For Each s As String In Directory.GetFi les(RootDirecto ry)
'******* Perform task on file s here. Replace with your
own file
'******* manipulation code here
Next

For Each s As String In Directory.GetDi rectories(RootD irectory)

'Correct me if I'm wrong Herfried but this line prevents
recursion into
'empty folders
If Not (File.GetAttrib utes(s) And
FileAttributes. ReparsePoint) = _
FileAttributes. ReparsePoint Then

'***** Perform work in folder s here. Replace with
your
'***** folder manipuation code here

'Notice we're calling ourself here to get data on child
folders
'This is the recursive part!
EnumerateDirect ory(s)
End If
Next
End Sub
End Module
BTW: Why are you using substring parse out the portions of your
folders and filename? why not use the methods in the System.IO
namespace?

For example, instead of:

mrootPath = d.Substring(0, d.LastIndexOf(" \"))

use this instead:

mrootPath = Path.GetPathRoo t(d)

and instead of

mFileName = f.Substring(f.L astIndexOf("\") + 1)

use this instead:

mFileName = Path.GetFileNam e(f)

Nov 21 '05 #8

C:\Base\Level1\ level2\level3\L evel4\Filename. TXT
C:\Base is the base (root) dir.
I need to parse the folder name Level1 thru level4 and assign a
corresponding folder level ID 2,3,4) to these folders.

Any idea how to do this?
Thanks in advance.

Do something like this (one I prepared earlier... you don't need to use XML.
To add the folder level counter add a line to increment a class-level counter
inside the recursion loop and include its value in the output:

Private Function GetFiles(ByRef XmlDoc As XmlDocument, ByRef ParentNode
As XmlElement, ByVal DirPath As String, Optional ByVal IncludeSubFolde rs As
Boolean = True) As XmlNode

Dim objFileInfo As FileInfo
Dim objDir As DirectoryInfo = New DirectoryInfo(D irPath)
Dim objSubFolder As DirectoryInfo

'add a node for each file
For Each objFileInfo In objDir.GetFiles ()
Dim MyFileNode As XmlElement = XmlDoc.CreateEl ement("Node")
MyFileNode.SetA ttribute("type" , "file")
MyFileNode.SetA ttribute("id", intCount.ToStri ng)
intCount += 1
MyFileNode.SetA ttribute("type" , objFileInfo.Ext ension)
MyFileNode.SetA ttribute("size" , objFileInfo.Len gth.ToString)
MyFileNode.SetA ttribute("text" , objFileInfo.Nam e)
ParentNode.Appe ndChild(MyFileN ode)
Next

'call recursively to do sub folders
'if you don't want this set optional
'parameter to false

'add the folder node
If IncludeSubFolde rs Then
For Each objSubFolder In objDir.GetDirec tories()
Dim DirNode As XmlElement = XmlDoc.CreateEl ement("Node")
DirNode.SetAttr ibute("type", "folder")
DirNode.SetAttr ibute("id", intCount.ToStri ng)
intCount += 1
DirNode.SetAttr ibute("text", objSubFolder.Na me)
ParentNode.Appe ndChild(DirNode )
GetFiles(XmlDoc , DirNode, objSubFolder.Fu llName, True)
Next
End If

Return ParentNode

End Function
Nov 21 '05 #9
Stuart;

Sorry for my very late response. I'd been away for a long period of time.
Thanks for your help!

Bill

"Stuart Irving" <Stuart Ir****@discussi ons.microsoft.c om> wrote in message
news:62******** *************** ***********@mic rosoft.com...

C:\Base\Level1\ level2\level3\L evel4\Filename. TXT
C:\Base is the base (root) dir.
I need to parse the folder name Level1 thru level4 and assign a
corresponding folder level ID 2,3,4) to these folders.

Any idea how to do this?
Thanks in advance.

Do something like this (one I prepared earlier... you don't need to use
XML.
To add the folder level counter add a line to increment a class-level
counter
inside the recursion loop and include its value in the output:

Private Function GetFiles(ByRef XmlDoc As XmlDocument, ByRef ParentNode
As XmlElement, ByVal DirPath As String, Optional ByVal IncludeSubFolde rs
As
Boolean = True) As XmlNode

Dim objFileInfo As FileInfo
Dim objDir As DirectoryInfo = New DirectoryInfo(D irPath)
Dim objSubFolder As DirectoryInfo

'add a node for each file
For Each objFileInfo In objDir.GetFiles ()
Dim MyFileNode As XmlElement = XmlDoc.CreateEl ement("Node")
MyFileNode.SetA ttribute("type" , "file")
MyFileNode.SetA ttribute("id", intCount.ToStri ng)
intCount += 1
MyFileNode.SetA ttribute("type" , objFileInfo.Ext ension)
MyFileNode.SetA ttribute("size" , objFileInfo.Len gth.ToString)
MyFileNode.SetA ttribute("text" , objFileInfo.Nam e)
ParentNode.Appe ndChild(MyFileN ode)
Next

'call recursively to do sub folders
'if you don't want this set optional
'parameter to false

'add the folder node
If IncludeSubFolde rs Then
For Each objSubFolder In objDir.GetDirec tories()
Dim DirNode As XmlElement = XmlDoc.CreateEl ement("Node")
DirNode.SetAttr ibute("type", "folder")
DirNode.SetAttr ibute("id", intCount.ToStri ng)
intCount += 1
DirNode.SetAttr ibute("text", objSubFolder.Na me)
ParentNode.Appe ndChild(DirNode )
GetFiles(XmlDoc , DirNode, objSubFolder.Fu llName, True)
Next
End If

Return ParentNode

End Function

Nov 21 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
28267
by: Eric Martin | last post by:
Hello, Does anyone know of a way to loop thru a SQL table using code in a stored procedure? I need to go thru each record in a small table and build a string using values from the fields associated with a part number, and I can't find any way to process each record individually. The string needs to be initialized with the data associated with the 1st record's part number, and I need to build the string until a new part number is...
5
4036
by: Andrew Young | last post by:
How do I loop thru a result set Without using a curosr?
1
6255
by: Jeremy Langworthy | last post by:
Hi I have a dynamicly generated form (well the elements are at least) that looks something like this: while( not end of returned records): <input name="plan_id" type="checkbox" id="" value="<?= $row_plans->planid ?>">
3
2874
by: Pete Gomersall | last post by:
Hi All, I have seen many examples of deleting folders with subfolders and files. (system.io.directory/info etc delete method) However, I cannot find a decent code example which will work where some folders/files maybe read only or hidden. I know, basically have to change the file attributes to normal. Has anyone a good example of a URL for a good example? Cheers, Pete Gomersall
4
2186
by: VB Programmer | last post by:
How can I loop thru all textboxes on a form? I want to remove any single quotes in the data entry. I was thinking something like this: For Each c As Control In Me.Controls Dim t As TextBox = CType(c, TextBox) t.Text = t.Text.Replace("'", "") Next
2
1526
by: Michael Beck | last post by:
I am new to .net programming and I want to know if I can loop thru a specified number of controls on an html form. In Access, the code looks like this: For i = 1 to 10 Me("txtAlternate" & i) = "" Next i Is there an equivalent code in asp.net?
6
1949
by: doncee | last post by:
Using a multi select list box to open several records in a pre - defined form. Most of the code that follows is taken from a posting by Alan Browne on his web site. The click routine is supposed to loop thru all of the reports, or in this case records, selected in the list box & display them for previewing or editing. In my situation it only displays 1 record in the form & does not perform the necessary loop. Have tried futzing with it...
3
1023
by: Marc Miller | last post by:
Hi all, I need to store a list of modules.functions() in an array and then loop thru the array and call the functions. I have not been able to get any code to work. Here's what I need to do: dim myArr(3) as string myArr(0) = "MyModA.Func1()"
2
1804
by: fniles | last post by:
I would like to loop thru all the files in a folder. For ex: I have a folder c:\temp and inside that folder there are many zip files. I want to read each zip files in c:\temp. How can I do that ? Thank you.
0
8454
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8785
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8644
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7389
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6200
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5671
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4200
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2776
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2012
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.