The ASP Emporium
Free Active Server Applications and Examples by Bill Gearhart
Online since Friday January 7, 2000

 home > code > code library > Path Manipulation > WinPath Object

enter a phrase to search: (advanced search)


 h o m e 

 w h a t 's  n e w 

 a l l   c o d e 
  .net:
    • Fundamentals
    • C# Classes
  classic asp:
    • Code Library
    • ASP Apps
  general:
    • Tutorials
    • SQL

 d o w n l o a d s 

 u s e r   f o r u m s 

 l i n k s 

 s e a r c h 

 s u p p o r t 


WinPath Object   v1.0   [JScript]

< prev proc
UnMappath Function
next proc >
Browsr Function

purpose:
WinPath allows a developer to manipulate, test and return information 
about an entered absolute path.
syntax:
var object = new WinPath(pathToTest);
example usage:
var myPath = new WinPath(Server.Mappath("./file.asp"));
if (myPath.hasValidSyntax( )) {
	if (myPath.exists( )) {
		Response.Write("<A HREF=\"" + myPath.getVirtualPath( ))
		Response.Write("\">go here<\/A>");
	} else {
		Response.Write(myPath.getPathType( ))
		Response.Write(" path doesn't exist on this server!");
	}
} else {
	Response.Write("Path has bad syntax! Please fix.");
}
source code:
/*
WinPath Object v1.0 [JScript]
http://www.aspemporium.com/aspEmporium/examples/jscript/index.asp



Purpose:
	WinPath allows a developer to manipulate, test and return
	information about an entered absolute path.



Version History:
	Version 1.0 
		Initial Release - 1/12/2001



Syntax:
	Syntax 1:
		var [variable] = new WinPath([absolutePath]);
	or
	Syntax 2:
		var [variable] = new WinPath();



Properties:
	[variable].absolutePath = [new absolute path]
		represents the absolute path to test or return
		information about [string]. This property
		is optional if the variable is declared with
		the absolutePath argument already entered as in
		syntax 1 above.



Methods:
	[variable].hasValidSyntax( )
		checks the entered absolute path for proper syntax.
		It is recommended that you call this method before
		using any other methods of WinPath as most of the
		other methods will require a valid directory path
		to perform reliably. [boolean]

	[variable].getVirtualPath( )
		returns the virtual equivalent of an entered absolute
		path [string]

	[variable].getAbsolutePath( )
		returns the entered absolute path. equivalent to the
		absolutePath property but read only... [string]

	[variable].exists( )
		tests the absolute path's existence on the server.
		returns true if the specified file/directory is found.
		otherwise returns false. Exists will return the error
		description returned if a runtime error is supressed
		when the scripting runtime library is attempting to be
		controlled programmatically by the WinPath object. How's
		that for a run-on sentence... This error can be supressed
		further by testing for it in your code, ensuring that the
		error won't cause further errors that are not trapped 
		in other methods of the WinPath object.
		[boolean/string - ErrorDescription]

		Example illustrating testing for errors returned by the
		exists( ) method of WinPath:
			
		    var a = new WinPath();
		    a.absolutePath = "c:\inetsrv\www";
		    if (a.hasValidSyntax( )) {
			var b = a.exists( );
			var errorMsg1 = "automation server can't create object";
			if (b.toLowerCase() == errorMsg1){
				with (Response) {
					Write("scripting run-time library ")
					Write("not registered on this server! ")
					Write("cannot continue");
					End( );
				}
			} else {
				if (!b) {
					with (Response) {
						Write("path not found");
						End( );
					}
				}
			}
			... <-- anything that makes it here is a path with
			        valid syntax that exists. just another way
			        to cover your ass and keep the bad data from
			        messing up the rest of the program's flow.
			        You might also want to check for the dreaded
			        "permission denied" error as well...
		    }

	[variable].getPathType( )
		returns a string indicating the type of path entered.
		return value will either be "file", "drive" or 
		"directory" and will always be lowercase.

	[variable].WinPathObject_Version( )
		returns a string representing the current version of the
		WinPath object. Will always be in the format:
		"major version number.minor version number"



Example Usage:
	var myPath = new WinPath(Server.Mappath("./file.asp"));
	if (myPath.hasValidSyntax( )) {
		if (myPath.exists( )) {
			Response.Write("<A HREF=\"" + myPath.getVirtualPath( ))
			Response.Write("\">go here<\/A>");
		} else {
			Response.Write(myPath.getPathType( ))
			Response.Write(" path doesn't exist on this server!");
		}
	} else {
		Response.Write("Path has bad syntax! Please fix.");
	}



Requirements:
	- Microsoft JScript Scripting Engine version 5.5 or better.
	- Scripting Run Time Library (Scripting.FileSystemObject).



Known Bugs:
	- There are no known bugs.



Disclaimer/Notes:
	You are bound to the ASP Emporium Source Code License
	and take/use/think about/alter/breathe-near/etc... this
	software at your own risk with no promises and no guarantees.

	http://www.aspemporium.com/aspEmporium/help/license.asp


	Please check around the help area first before sending
	me feedback asking for help using this object:

	http://www.aspemporium.com/aspEmporium/help/index.asp
	http://www.aspemporium.com/aspEmporium/feedback/index.asp


	Please post suggestions/bug fixes/reports or whatever
	to the developer's forum:

	http://www.aspemporium.com/aspEmporium/forum/display_forum.asp?fid=7



*/
// ------------------------
// start object declaration
// ------------------------

function WinPath(absPath) {
	// this is a special keyword that specifies
	// the WinPath object once it is created.
	// That way we can use the "new" statement:
	// var [variable] = new WinPath([absolute path name]);
	this.absolutePath = absPath;
}

function isWindowsPath() {
	// this regular expression validates path syntax and:
	// - Ensures there are no illegal characters in each 
	//   directory or file name in the path:  \/:*?"<>|
	// - Makes sure that the path does NOT end with a 	
	// - Verifies that the path starts with a good drive
	//   letter (Windows permits a drive to have one 
	//   letter, anywhere from A to Z)
	// - Guarantees that directories are separated by \'s,
	//   NOT /'s

	var path = this.absolutePath;
	if (path.length == 3) {
		//validate just the drive root
		var re = /^[A-Za-z]:\\$/
	} else {
		//validate drive and path
		var re = /^[A-Za-z]:(\\([^\/\\:\*\?\"<>\|]+)[^\\])+$/
	}
	return re.test(path);
}

function unMappath() {
	// takes an absolute path and returns it's virtual
	// path equivalent. The path must be available in
	// the public server space. For example, if your
	// server was mapped to c:\wi\f and the path you
	// entered was c:\wi\f\f\v\c\s\e.asp then unMappath
	// would return /f/v/c/s/e.asp. You could use that
	// to create an anchor link to the entered absolute
	// path in an html document, for example...

	// This is one of the most useful ASP functions ever.
	// I also have a VBScript version somewhere on the 
	// site. Search for:   unmappath     if you want it.

	var path = this.absolutePath;
	var tmp = "", strroot = Server.Mappath("/");
	path = path.toLowerCase();
	tmp = path.replace(strroot.toLowerCase(), "")
	tmp = tmp.replace(/\\/gi, "/");
	if (tmp.length == 0) {tmp += "/"}
	if ((!isFile()) && (!isDrive())) {
		// add that last / to the path if it's 
		// a directory path and it's not there.
		// failure to put the last / forces the
		// server to call the page twice, resulting
		// in more overhead in the long run.
		var re = /\/$/i
		if (!re.test(tmp)) {tmp += "/";}
	}
	return tmp;
}

function getAbsPath() {
	// returns the absolute path entered when the WinPath
	// object was first created.
	return this.absolutePath;
}

function isFile() {
	// once again, more regular expressions...
	// Did you ever notice that most of my JScript examples
	// are built around regular expressions? That's not by
	// accident... JScript's string parsing methods aren't 
	// the best and nothing beats regular expressions in
	// any language. VBScripts RegExp object is bulky compared
	// to JScript's Regular Expression object. Now the most
	// complicated string parsing logic is only 2 lines...

	// this bad boy determines if the entered path is a file
	// or a folder by checking the end of the path for a period
	// and anywhere from 2 to 5 characters after the period.
	// Theoretically that could still be a directory but only
	// a fool labels their directories with periods. Use
	// underscores instead. This will recognise file extensions
	// with anywhere from 2 to 5 characters like mp3, js, class,
	// vbs, poop, etc...

	var re = /\.[\d\D]{2,5}$/i
	return re.test(this.absolutePath);
}

function isDrive() {
	// check to see if the entered absolute path is a drive only:
	// c:\ or whatever. will return false if the path contains a
	// drive letter along with either folders or files or if the
	// absolute drive path has bad syntax.
	var re = /^[A-Za-z]:\\$/
	return re.test(this.absolutePath);
}

function getPathTypeByAbsolutePath() {
	// use the nifty isFile function above to do all the work
	// and return a readable name for the entered path's type.
	// This isn't unusual as JScript often prints phrases like
	// Undefined and Null instead of numbers or codes that 
	// programmers are used to checking for in code (If this
	// was vbscript, i'd probably have it return 1 for file
	// and 0 for directory or something like that). Anyways...

	if (isFile()) {
		return "file";
	} else {
		if (isDrive()) {
			return "drive";
		} else {
			return "directory";
		}
	}
}

function appVersion() {
	// keep track of the current version...
	// all part of my new attempt (plan #452456) at organizing
	// the site since I'm getting lost in it as I add new stuff
	// and make new sections.
	return "1.0";
}

function pathExists() {
	// once again use isFile to determine the type of path.
	// If it's a folder, check for the directory. If it's a
	// file, check for the file..., drive check drives, etc...
	// added some error handling to make it more interesting...

	try {
		var f = new ActiveXObject("Scripting.FileSystemObject");
	} catch(e) {
		return e.description;
	}
	if (isFile()) {
		return f.fileExists(this.absolutePath);
	} else {
		if (isDrive()) {
			return f.driveExists(this.absolutePath);
		} else {
			return f.folderExists(this.absolutePath);
		}
	}
}

// Export public methods of this object.
// prototype allows us to define the available
// methods that the WinPath Object exposes.
// follows this format:
//   [object declaration function].prototype.[exposed method name] = function name;

WinPath.prototype.hasValidSyntax = isWindowsPath;
WinPath.prototype.getVirtualPath = unMappath;
WinPath.prototype.getAbsolutePath = getAbsPath;
WinPath.prototype.exists = pathExists;
WinPath.prototype.getPathType = getPathTypeByAbsolutePath;
WinPath.prototype.WinPathObject_Version = appVersion;

// ------------------------
// end object declaration
// ------------------------
< prev proc
UnMappath Function
next proc >
Browsr Function