Thread: GetFiles() Help
View Single Post
  #2 (permalink)  
Old April 5th, 2008, 01:51 AM
Imar's Avatar
Imar Imar is offline
Wrox Author
Points: 70,322, Level: 100
Points: 70,322, Level: 100 Points: 70,322, Level: 100 Points: 70,322, Level: 100
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jun 2003
Location: Utrecht, Netherlands.
Posts: 17,089
Thanks: 80
Thanked 1,576 Times in 1,552 Posts
Default

Hi Adam,

There are a couple of ways to do this. First of all, you can use the static GetFiles method of the Directory class and pass it a search pattern. This only gives you the name of the file as a string though:
Code:
Dim basePath As String = Server.MapPath("~/")
Dim searchPattern As String = "*.aspx"

dgArticleList.DataSource = Directory.GetFiles(basePath, searchPattern)
dgArticleList.DataBind()
Alternatively, you can do the same with your code and pass the wild card pattern to GetFiles of your DirectoryInfo instance:
Code:
' Assumes you have basePath and searchPattern from example 1
Dim dirInfo As New DirectoryInfo(basePath)
dgArticleList.DataSource = dirInfo.GetFiles(searchPattern)
dgArticleList.DataBind()
Finally, and much cooler you can use LINQ (if you are using .NET 3.5). With LINQ you can express queries in a much more natural way and get files based on much more criteria than their extension alone. Just for fun, the following code gets all ASPX files that have been created in the past 24 hours and that have been accessed in the last 10 minutes:
Code:
Dim list = From f In New DirectoryInfo(basePath).GetFiles _
    Where f.CreationTime > DateTime.Now.AddHours(-24) _
    And f.LastAccessTime > DateTime.Now.AddMinutes(-10) _
    And f.Extension.EndsWith(".aspx", StringComparison.InvariantCultureIgnoreCase) _
    Select f

  dgArticleList.DataSource = list
  dgArticleList.DataBind()
  Hope this helps,

Imar


---------------------------------------
Imar Spaanjaars
http://Imar.Spaanjaars.Com
Everyone is unique, except for me.
Author of Beginning ASP.NET 3.5 : in C# and VB, ASP.NET 2.0 Instant Results and Dreamweaver MX 2004
Want to be my colleague? Then check out this post.