Selecting a Random File from a Directory and Outputting its Contents Demo

This demo illustrates how to have a random text file read from a directory and have its contents displayed. Below you will see the output of a random text file from the directory of (very) old WebWeekly issues.


WebDaily: Your daily source for Web Technology Tips and Tricks! -Forward this email and subscription information to a fellow developer! ---- CALL FOR AUTHORS!! ---- ---- If you'd like to write for 4GuysFromRolla.com ---- visit http://www.4GuysFromRolla.com/contribute ---- to learn more! ********************************************************************** Why I like DateSerial*********************************************************************** This article discusses why, exactly, I like DateSerial!There are some very neat and nifty functions in ASP that many people takefor granted. One such function, in my opinion, is DateSerial. To me,this is one of the neatest and most powerful functions I've run across inASP / VBScript.DateSerial, in case you don't know, is a function used to create a date.It takes three parameters: the year, month, and day of the date you wantto create. For example, say that you wanted to store the date of thesigning of the Declaration of Independence. You could write some codewhich looks like this: Dim DecIndepDate DecIdepDate = DateSerial(1776, 7, 4)This creates the date July 4, 1776 (or #7/4/1776#) and stores it in thevariable DecIndepDate.At first glance, DateSerial may not seem that useful or powerful or eventhat neat, but it really is. The power of DateSerial comes into focuswhen you are asked to get some date like the last day of the previousmonth.While it is true that you could construct a simple conditional statementto determine the current month, and see what the previous month was, andwhat was the last day, you can do this in one line with DateSerial. DateSerial(Year(Date), Month(Date), 1 - 1)This would return the first day before the first day of the current monthof the current year; in other words the last day of the month previous.Again, this may not seem like to big of a hub-bub, but it is! Imaginethat you were asked to find what day of the week it was on the first day of the previous month of the previous year. This is simple withDateSerial and DatePart.(If you are unfamiliar with DatePart, it extracts a "part" of a datevariable. You can ask for the weekday, the month, day, year, week,quarter, etc. For example, DatePart("m",DateSerial(1776,7,4)) wouldreturn the month of 7/4/1776, which is 7.)Here is the code: 'Get the weekday of the first day of the previous month of the 'previous year DatePart("w", DateSerial(Year(Date) - 1, Month(Date) - 1, 1))And the neatest, neatest part of DateSerial is that you can form reallyconfusing-sounding sentences when you use DateSerial. Here is anexample which fully illustrates that confusing neatness: DateSerial(Year(Date) - 1, Month(Date) - 2, 1 - 1)If asked what the above statement of code did, you could aptly reply: "It returns the first day before the first day of the month twomonths previous from the current month from the year previous to thecurrent year."And then your colleauges will be amazed and envious of your date-jargon.(It would be easier to explain the above line of code as returning thelast day of the month a year and three months ago from the current date,but then that wouldn't be as neat, now would it?)If you have any questions, comments, or ideas, please let me know bysimply replying to this email!Happy Programming!****************************************************************************************************************************************** To subscribe to WebDaily, point your browser to: http://www.4GuysFromRolla.com/webtech/webdaily To unsubscribe from WebDaily, reply to this email with the following subject: UNSUBSCRIBE WEBDAILY******************************************************************************************************************************************Thank you for subscribing to WebDaily!If you know someone who could benefit from a wealth of web developmenttechnology, invite them to visit http://www.4GuysFromRolla.com/new


Source Code
<%
Option Explicit

Function ReadDir(FolderName)
	On Error Resume Next
	Dim objFSO
	Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
		
	'Make sure the specified folder exists
	If Not objFSO.FolderExists(FolderName) Then
		ReadDir = "Folder does not exist. <br><b>This can be changed to " & _
				"a default message or nothing.</b>"
		Exit Function
	End If

	Dim objFolder
	Set objFolder = objFSO.GetFolder(FolderName)

	Dim I : I = -1
	ReDim arrFile(20)
	Dim objFile
	For Each objFile In objFolder.Files
		If Right(objFile, 4) = ".txt" Then
  			I = I + 1
			
			if I > UBound(arrFile) then ReDim Preserve arrFile(I + 20)
						
			arrFile(I) = objFile.Path
		End If
	Next
	
	'Make sure arrFile is the right size
	Redim Preserve arrFile(I)

    If I = -1 Then
		ReadDir = "No text files in this directory. <br><b>This can be " & _
		          "changed to a default message or nothing.</b>"
		Exit Function
	End If

	Randomize
	Dim RanFile : RanFile = Int((UBound(arrFile) - 1 + 1) * Rnd + 1)
	Dim strOutput : strOutput = ""
	Dim strFileName : strFileName = arrFile(RanFile)
	If objFSO.FileExists(strFileName) Then
		Dim objTextStream
		Set objTextStream = objFSO.OpenTextFile(strFileName, 1)
			Do While Not objTextStream.AtEndOfStream
				strOutput = strOutput & objTextStream.ReadLine
			Loop
		objTextStream.Close
	Else
		ReadDir = "File does not exist. <br><b>This can be changed to a " & _
		          "default message or nothing.</b>"
		Exit Function
	End If
 
	
    ReadDir = strOutput
 
 Set objTextStream = Nothing
 Set objFolder = Nothing
 Set objFile = Nothing
 Set objFSO = Nothing
End Function
%>

<h1>Selecting a Random File from a Directory and Outputting its Contents Demo</h1>
...

<%
  Response.Write(ReadDir(Server.MapPath("/webtech/WebDaily")))
%>


[Return to the User Tip]