File System Object - Dir Command

Is there a way using the ASP File System Object to do a "dir" (directory listing) on a folder on the web server?

I want the names of all the files in a specific folder.
Richard KortsAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

BadotzCommented:
Here is a server-side JavaScript page I use with Ajax to manipulate textfiles and directories.


<%@ Language="JavaScript"%>
<%
/*
 ######################################
 x_textfile.asp
 
 Read / write textfile
 
 Exposed methods
 --------------------------------------
 list_files
 list_folder
 list_folders
 create_folder
 read
 read_line
 write
 write_html
 write_lines
 process
 ######################################
 */
 
var X_TEXTFILE = (function() {
	var cREAD = 1,
		cWRITE = 2,
		cAPPEND = 8,
		cLINE_LENGTH = 90,
		fso = new ActiveXObject('Scripting.FileSystemObject');
	
	
	function get_fso() {
		return new ActiveXObject('Scripting.FileSystemObject');
	}
	
	
	function create_folder(how) {
		if (how.path !== '') {
			var smp = Server.MapPath(how.path);
			if (!fso.FolderExists(smp)) {
				fso.CreateFolder(smp);
			}
		}
	}
	
	
	function file_full_name(how) { 
		return Server.MapPath(how.path + how.file);
	}
	
	
	function file_exist(how) { 
		return fso.fileExists(file_full_name(how)); 
	}
	
	
	function file_delete(how) { 
		if (file_exist(how)) {
			fso.DeleteFile(file_full_name(how), how.del_readonly);
		}
	}
	
	
	function read_file(how) {
		var ts;
		
		if (file_exist(how)) {
			ts  = fso.OpenTextFile(file_full_name(how), cREAD, how.make, how.format);
			return ts.ReadAll();
		}
		return '';
	}
	
	
	function read_line(how) { // fname, fpath, line, inc) {
		var line = +how.line,
			ts,
			text = [];
		
		if (file_exist(how)) {
			ts  = fso.OpenTextFile(file_full_name(how), cREAD, how.make, how.format);
			
			do {
				text.push(ts.ReadLine());
			} while (--line >= 0);
			
			if (how.include !== '') {
				return text.join('\n'); // Lines up to line "n"
			}
			return text.pop(); // Only line "n" (the last line)
		}
		return '';
	}
	
	
	function write_html(how) { // fpath, fname, txt) {
		var retval = '',
			ts;
		
		create_folder(how); // If the folder does not exist, make it
		
		if (how.purge) {
			file_delete(how);
		}
		try {
			ts = fso.OpenTextFile(file_full_name(how), cWRITE, how.make, how.format);
			
			ts.WriteLine(how.text);
			ts.Close();
		}
	    
		catch(e) { retval = e.description; }
	    
		return retval;
	}
	
	
	function write_line(how) { // fpath, fname, txt, purge) {
		var retval = '',
			ts;
		
		create_folder(how); // If the folder does not exist, make it
		
		if (how.purge) {
			file_delete(how);
		}
		try {
			ts = fso.OpenTextFile(file_full_name(how), cAPPEND, how.make, how.format);
			
			ts.WriteLine(how.text);
			ts.Close();
		}
		catch(e) { retval = e.description; }
	    
		return retval;
	}
	
	
	function write_lines(how) {
		var retval = '',
			line = 0,
			ts;
		
		create_folder(how); // If the folder does not exist, make it
		
		try {
		    ts = fso.OpenTextFile(file_full_name(how), cAPPEND, how.make, how.format);
			
			for (line = 0; line < how.text.length; line++) {
			    ts.WriteLine(how.text[line]);
			}
		    ts.Close();
		}
	    catch(e) {
			retval = e.description;
	    }
	    return retval;
	}
	
	
	function list_files(how) {
		try {
			var stack = [],
				folder = fso.getFolder(Server.MapPath(how.path)),
				enu;
			
			for (enu = new Enumerator(folder.Files); !enu.atEnd(); enu.moveNext()) {
				stack.push(enu.item());
			}
			if (stack.length > 0) { 
				return stack.join('\n'); 
			}
			return [];
		}
		catch(e) { 
			stack.push(e.description); 
			return stack.join('\n'); 
		}
	}
	
	
	function list_folder(how) {
		var files = [],
			stack = [],
			folder,
			enu;
		
		how.path = ((how.path === '') ? '.' : how.path);
		
		try {
			files.push(fso.getFolder(how));
			stack.push(fso.getFolder(how));
			
			while (stack.length > 0) {
				folder = stack.pop();
				
				for (enu = new Enumerator(folder.SubFolders); !enu.atEnd(); enu.moveNext()) {
					try { stack.push(enu.item()); }
					catch(e) {}
				}
				for (enu = new Enumerator(folder.Files) ; !enu.atEnd(); enu.moveNext()) {
					try { files.push(enu.item().Path); }
					catch(e) {}
				}
			}
		}
		catch(e) {}
		finally {
			if (files.length > 0) { 
				return files.join('\n'); 
			}
			return [];
		}
	}
	
	
	function list_folders(how) {
		var found = [],
			stack = [],
			folder,
			enu;
		
		how.path = ((how.path === '') ? '.' : how.path);
		
		try {
			folder = fso.getFolder(how.path);
			
			found.push(folder);
			stack.push(folder);
			
			while (stack.length > 0) {
				folder = stack.pop();
				
				for (enu = new Enumerator(folder.SubFolders); !enu.atEnd(); enu.moveNext()) {
					try {
						stack.push(enu.item());
						found.push(enu.item());
					}
					catch(e) {}
				}
			}
		}
		catch(e) {}
		finally {
			if (found.length > 0) { return found.join('\n'); }
			
			return [];
		}
	}
	
	
	function process(arg) {
		// Set parameters for consistency
		var how = arg || {},
			result;
		
		how.method			= arg.method		|| '';
		how.path			= how.path			|| '';
		how.file			= how.file			|| '';
		how.del_readonly	= how.del_readonly	|| false;	// "true"	= delete READONLY file
		how.make			= how.make			|| true;	// "false"	= do not create non-existant before access
		how.format			= +how.format		|| 0;		// "0"		= ASCII; "-1" = UNICODE; "-2" = system default
		how.purge			= how.purge			|| false;	// "TRUE"	= delete content before writing
		how.line			= +how.line			|| 0;		// "0" to return last line read, "n" to return "n" lines
		how.include			= how.include		|| '';		// ""		= last line; "y" = Lines up to line "n"
		
		// If there is a path, add a final "/"
		if (how.path !== '') {
			if (how.path.substr(how.path.length - 1) !== '/') {
				how.path += '/';
			}
			if (how.file.length > 0) {
				while (how.file.substr(0, 1) === '/') {
					how.file = how.file.substr(1);
				}
			}
		}
		// What do they want us to do?
		switch (how.method) {
			case 'list_files':
				result = list_files(how);
				break;
			case 'list_folder':
				result = list_folder(how);
				break;
			case 'list_folders':
				result = list_folders(how);
				break;
			case 'create_folder':
				result = create_folder(how);
				break;
			case 'read':
				result = read_file(how);
				break;
			case 'read_line':
				result = read_line(how);
				break;
			case 'write':
				result = write_line(how);
				break;
			case 'write_html':
				result = write_html(how);
				break;
			case 'write_lines':
				result = write_lines(how);
				break;
		}
		return result;
	}
	
	
	return {
		'list_files'	: function(arg) { arg.method = 'list_files';	return process(arg); },
		'list_folder'	: function(arg) { arg.method = 'list_folder';	return process(arg); },
		'list_folders'	: function(arg) { arg.method = 'list_folders';	return process(arg); },
		'create_folder'	: function(arg) { arg.method = 'create_folder';	return process(arg); },
		'read'			: function(arg) { arg.method = 'read';			return process(arg); },
		'read_line'		: function(arg) { arg.method = 'read_line';		return process(arg); },
		'write'			: function(arg) { arg.method = 'write';			return process(arg); },
		'write_html'	: function(arg) { arg.method = 'write_html';	return process(arg); },
		'write_lines'	: function(arg) { arg.method = 'write_lines';	return process(arg); },
		//
		'process'		: function(arg) { return process(arg); },
		//
		'dummy'			: null  /* dummy object closer  */
	};
})();
%>

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
CumbrowskiCommented:
ANY Folder on the Server or only Folders of the current web site?

If you only want yo access the files of the current web site, then you can use the filesystem object directly.See First part of the sample code.

IIf you want to see files and folders outside the current web site and  you have WMI enabled on the web server and permission to execute it by the web user, then you could use the second code example. I actually hope that your IIS user does not have permission. In that case you should use windows authentication for the part of the site where you run the file management code and login with a user that has the necessar permission on that server.


<%
 
'File System Object Example
 
Dim oFso: Set oFso = Server.CreateObject("Scripting.FileSystemObject")
Dim sInpPath: sInpPath =  Server.MapPath("\")
Dim oFold
Set oFold = oFSO.GetFolder(sInpPath)
 
ShowFiles oFold.Path
ShowSubFolders oFold
 
Sub ShowSubFolders(Folder)
Dim SubFolder
 
    For Each Subfolder in Folder.SubFolders
          response.write SubFolder.Path & "<br><br>"
          ShowFiles Subfolder.Path
          ShowSubFolders Subfolder
    Next
End Sub
 
Sub ShowFiles(sPath)
Dim oFile, oFolder
  Set oFolder = oFSO.GetFolder(sPath)
  For each oFile in oFolder.Files
    response.write oFile.Name & "   " & oFile.Size & "<br>"
  Next
   Set oFolder = Nothing
End Sub
 
'WMI Example
 
strComputer = "."
Set objWMIService = Server.GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * from Win32_Directory")
For Each objItem in colItems
   response.write "Caption: " & objItem.Caption & "<br>"
Next
 
'List of Files in Folder
set colFiles = objWMIService.ExecQuery("Select * from CIM_DataFile where Path = '\\temp\\'")
 
'List of Sub Folders
Set colSubfolders = objWMIService.ExecQuery _
    ("Associators of {Win32_Directory.Name='c:\scripts'} " _
        & "Where AssocClass = Win32_Subdirectory " _
            & "ResultRole = PartComponent")
 
For Each objFolder in colSubfolders
    response.write objFolder.Name & "<br>"
Next
	
%>

Open in new window

0
Richard KortsAuthor Commented:
I used a different approach. You get the points for your efforts.
0
Cloud Class® Course: Microsoft Office 2010

This course will introduce you to the interfaces and features of Microsoft Office 2010 Word, Excel, PowerPoint, Outlook, and Access. You will learn about the features that are shared between all products in the Office suite, as well as the new features that are product specific.

BadotzCommented:
There is no sense in awarding points if you discovered a different solution. But since you mentioned it, kindly show us the code.
0
Richard KortsAuthor Commented:
To all,

I awarded points because in the past when I didn't I've gotten a lot of crap with negative comments, etc.

The solution was that I put a new table in the database that records the file name whenever its created, so I read that table & give the user a choice of which bacup to restore from.
0
CumbrowskiCommented:
Hi rKorts,

Thanks for the points and good to hear that you found an alternative solution that works for you. It's still not 100% clear to me was your original problem was where reading a directory would have been one solution, but you do not have to elaborate on it, if you don't want to. From how it sounds to me, is the folder that you wanted to access outside the web folder of the web site, thus no direct access to it available via the standard file-system object by ASP.

The WMI option that I proposed as solution for that problem might still be something to think about. It would require that the ASP scripts used will be executed by an authenticated user on the machine and not the user that is used by IIS for the normal anonymous HTTP access to the public web site.

I don't know how reliable the script/tool/feature or whatever you are using to track the file creations in your database table is, but it seems to me that there could be a possible issue, if this script happens to fail for whatever reason and miss to write the necessary information to your database. I don't know the dependencies, but if it is critical, then I would not recommend to solely rely on this "indirect" solution without any fail-safe backup available.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP

From novice to tech pro — start learning today.