I needed to create a list of all Code Snippets we ship in Visual Studio the other day containing their title, description and path on disc and size. As you might know, Code Snippets are stored in multiple directories below "%ProgramFiles%\Microsoft Visual Studio 10.0" so I had to traverse all the subdirectories of the aforementioned path to find all snippets.
Fortunately – linq to the rescue – this came down to a few lines of code :-)
Dim query = From file In My.Computer.FileSystem.GetFiles("C:\Program Files\Microsoft Visual Studio 10.0", FileIO.SearchOption.SearchAllSubDirectories) _
Where file.EndsWith(".snippet") _
Order By file
This statement gives you a List of Strings (or, to be a bit more precise, a System.Linq.IOrderedEnumerable(Of String)) which you can walk over to do all kinds of crazy things.
Here is what I did to solve the problem I described above:
Imports <xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim query = From file In My.Computer.FileSystem.GetFiles(txtPath.Text, FileIO.SearchOption.SearchAllSubDirectories) _
Dim snippets As New List(Of Snippet)
Dim snippetDocument As XElement
Dim snippet As Snippet
For Each item In query
snippetDocument = XElement.Load(item)
If snippetDocument...<Title>.Value IsNot Nothing Then
snippet = New Snippet With {.Title = snippetDocument...<Title>.Value.ToString _
, .Description = snippetDocument...<Description>.Value.ToString _
, .Path = item _
, .Size = New System.IO.FileInfo(item).Length}
snippets.Add(snippet)
End If
Next
DataGridViewSnippets.AutoGenerateColumns = True
DataGridViewSnippets.DataSource = snippets
End Sub
End Class
Public Class Snippet
Private _Title As String
Private _Description As String
Private _Path As String
Private _Size As Long
Public Property Title() As String
Get
Return _Title
End Get
Set(ByVal value As String)
_Title = value
End Set
End Property
Public Property Description() As String
Return _Description
_Description = value
Public Property Path() As String
Return _Path
_Path = value
Public Property Size() As Long
Return _Size
Set(ByVal value As Long)
_Size = value
Btw, if you bind the result to a DataGridView you can copy&paste from there into excel. Needo :-)
Cheers!
Daniel
P.S. If you'd like to understand why you need the Imports <xmlns="http... at the beginning of the code check the follow-up article I wrote.
P.P.S. You can download the source code from the MSDN Code Gallery.
Edited April 29, 2009: Included the "Imports" statement and did some cleanup work.
PingBack from http://asp-net-hosting.simplynetdev.com/how-to-get-a-list-of-all-files-of-a-directory-subdirectories-included/
Interesting Finds: April 24, 2009
Hi, I posted a bit of code the other day which I used to get a list of all Code Snippets we ship in Visual