'Get files from sub directory using vb.net
I have a directorry which contains many folders such as folder1,folder2,folder3 etc..which contains sub-directories..In that I have a folder name "special" which contains some files
Now I would like to get all those files based on the name of the sub-directory
Example:
C:\Users\desktop\Myfolder\folder1\special\
C:\Users\desktop\Myfolder\folder2\special\
C:\Users\desktop\Myfolder\folder3\special\
C:\Users\desktop\Myfolder\folder4\special\
Now I need to get all the files from each special folder of all the folder1,folder2,folder3 and folder4 and display them in gridview.
Solution 1:[1]
grid1.DataSource = (From p1 In IO.Directory.GetFiles("C:\Users\desktop\Myfolder\", "*", IO.SearchOption.AllDirectories)
Where p1.Contains("\special\"))
grid1.DataBind()
Solution 2:[2]
I just worked on your case, and i think the following piece of code will suits your requirement. The given code will drill through the directories and it display the filenames if it is comes under the special directory. Comment me back if i wrongly answered your question.
The procedure,
Private Sub GetFiles(ByVal xPath As String)
Try
If Directory.GetDirectories(xPath).Length > 0 Then
For Each xDir As String In Directory.GetDirectories(xPath)
If Directory.Exists(xDir) Then
GetFiles(xDir)
End If
Next
End If
If Directory.GetFiles(xPath).Length > 0 Then
For Each xDir As String In Directory.GetFiles(xPath)
If UCase(Path.GetDirectoryName(xDir)).EndsWith("SPECIAL") Then
MsgBox(Path.GetFileName(xDir))
End If
Next
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
and the call,
call GetFiles("D:\test")
Solution 3:[3]
if your datagridview is datagridview1 and countains two columns and you want to add the name file and last modified here is the solution ..
For Each sDir In Directory.GetDirectories("C:\Users\desktop\Myfolder\", "special", SearchOption.AllDirectories)
For Each File In Directory.GetFiles(sDir)
Dim detailedfile As New IO.FileInfo(File)
DataGridView1.Rows.Add(detailedfile.Name, detailedfile.LastAccessTime)
Next
next
if you want to add more details in the gridview you have just to add more columns and more integers in the DataGridView1.Rows.Add
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Chris Berlin |
| Solution 2 | |
| Solution 3 |
