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! ???????????????? GOT AN ASP QUESTION ????????????????? ????????????? Be sure to visit WebChat! ???????????? ? http://www.4GuysFromRolla.com/webtech/messageboard ? ??????????????????????????????????????????????????????********************************************************************** Intenal Storage of your SQL Server Objects*********************************************************************** This article deals with internal storage of SQL Server objects, plus itanswers a questioned asked by one of the WebDaily readers.This article will soon discuss some of the system catalogs of SQL server,but first I'd like to bring up a question posed to me by a WebDailyreader. After the last WebDaily about global.asa, one reader commentedthat he uses Notepad to write his ASP (which is the way it should be,check out http://www.4GuysFromRolla.com/misc for a funny GIF). In usingNotepad, he does not know how to write his Global.asa or where to put it.In answer to his question.... you need to put global.asa in the rootdirectory of your web application. A web application is, essentially, avirtual directory in IIS. If you are coding on your very own website (orhave root access), the root directory is /. If you have an account whereyou have your own directory, if your directory was set up as a virtualdirectory (as it probably was), you just need to put the global.asa filein your home directory.Global.asa is an optional file. If it is not there, no biggie. To addit, just FTP a file named global.asa to your directory. It's that simple.I provided examples of a valid global.asa file in the last WebDaily(available at http://www.4GuysFromRolla.com/webtech/113098-1.shtml). Itcould look as simple as: If anyone has any further questions, please feel free to reply to thisemail or to search for related information athttp://www.4GuysFromRolla.com/webtech.Now, onto SQL's system catalogs! This is not intended as an indepthcoverage of the system catalogs, just a quick overview showing you how youcan obtain some pretty powerful and useful information about the tables,columns, views, indexes, and other objects in your database. Thesysobjects table contains a row for every object in your database. Allthe table names (among other things) are stored in this table. Let's sayyou wanted to have an ASP page which printed all of the tables in adatabase set up with a DSN named TestDB. Here is the ASP code which couldaccomplish that: <% Dim conn, rs, sql Set conn = Server.CreateObject("ADODB.Connection") conn.Open "DSN=TestDB" sql = "SELECT name FROM sysobjects WHERE type='U'" Set rs = Conn.Execute(sql) Do While Not rs.EOF Response.Write rs(0) & "
" rs.MoveNext Loop %>The query retrieves all table names for the TestDB database. It is quiteobvious that we are asking sysobjects for all tables by asking for rows oftype 'U'. You can get all the views by asking for type 'V'.To see all of the rows in sysobjects, simply go to SQL and do a: USE my_database_name SELECT * FROM sysobjects To get a list of all of the columns for a given table, you need to go tothe system catalog syscolumns. The syscolumns table has a primary keyvalue named id, which is also a foreign key to sysobjects' primary key(also named id). So, let's say we have a table named Employee in ourdatabase, and we want to display all of the columns for that table. InSQL we could simply type: sp_help Employeebut that won't work in ASP without poking around for the right values.Rather, we could run this script: <% Dim conn, rs, sql Set conn = Server.CreateObject("ADODB.Connection") conn.Open "DSN=TestDB" sql = "SELECT SC.name FROM syscolumns SC " & _ "INNER JOIN sysobjects SO ON " & _ "SO.id = SC.id " & _ "WHERE SO.name = 'Employee' AND SO.type='U'" Set rs = Conn.Execute(sql) Do While Not rs.EOF Response.Write rs(0) & "
" rs.MoveNext Loop %>Pretty neat, eh? You can often find out what you need if you poke aroundlow enough. SQL, the standard query language, is a very neat and powerfulsyntax. In fact, I would not be surprised if God Himself spoke in termsof SQL. "SELECT LetThereBeLight FROM Miracles"If you have any questions, ideas, comments, or suggestions, please don'thesitate to reply to this email, letting me know of your inqueries. Also(!!), I am thinking of adding a "stump me" section to WebDaily, if fornothing else than to boost my ego. Basically those who have a question orparticularly difficult ASP problem could try to "stump" me with thequestion or problem. Please be aware that I will most likely respond notwith source code but with theory and ideas (for once you have the conceptsdown, coding is nothing but semantics). If you have a question you'd liketo try to stump me with, please send it to me by replying to this email!Have a great day, and 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]