Home :
Tutorials
Loop Through The Files In A Folder On Your Asp Net Server
Added by
David Coleman
on
18 March 2011
You may sometimes want to loop through all the files in a particular folder on your server. You might want to show files available for download or go through and delete images older than a year, for example. Just use the following code:
At the top of your page make sure you include the system.io namespace:
Imports System.IO
The following code should be placed wherever you want to loop through your files, e.g. on pageLoad or in a function.
'Tell your code where to find the folder you want to look inside.
'The ~ character simply means "the root of your website".
'Below, for example, "~/your-folder/" tells your code to look
'inside www.yourwebsite.co.uk/your-folder/.
Dim myFolder As New DirectoryInfo(Server.MapPath("~/your-folder/"))
'Loop through each file in the folder
For Each myFile As FileInfo In myFolder.GetFiles
'You can now access information about each file. Here are a few examples.
'Get the file's name
dim fileName as string = myFile.Name
'Get the file's extension, e.g. "jpg"
Dim fileExtension as string = myFile.Extension
'Get the date the file was created on
Dim creationTime as datetime = myFile.CreationTime
'Find out when the file was last changed
dim lastWriteTime as datetime = myFile.LastWriteTime
'Using one of the above examples, we can delete all files that are older than a year...
If myFile.CreationTime < DateTime.Now.AddYears(-1) Then
myFile.Delete()
End If
'Similarly, This extremely handy code deletes all files with 'banana' in the filename
If myFile.Name.ToLower.Contains("banana") Then
myFile.Delete()
End If
Next 'This takes us back to the start of the loop
There are no comments yet