2010-05-17

Generate a Unique File Name

Uses Two Other generic functions

This is a useful function to generate a unique file name. If the File object it is passed already exists then this function adds an underscore and a number from 02 to 99 to the base name of the file until it finds a unique file name. If no unique name can be generated, it returns null.

This function calls two other previously posted functions. The first determines the base name, or the name without the extension. The second pads a number to fill out a specified number of digits.

//
function uniqueFile (fileRef) {
//-------------------------------------------------------------------------
//-- U N I Q U E F I L E
//-------------------------------------------------------------------------
//-- Generic: Yes, for ExtendScript CS3 and newer
//-------------------------------------------------------------------------
//-- Purpose: To take a FileRef and check to see if it is unique. If yes,
//-- then return it, else add a suffix starting with _02 and keep trying
//-- until it is unique
//-------------------------------------------------------------------------
//-- Arguments: fileRef: a File object
//-------------------------------------------------------------------------
//-- Calls: Custom File method .nameWithoutExtension()
//-- Calls: pad
//-------------------------------------------------------------------------
//-- Returns: a File object. It might be the same one. If the function
//-- fails it returns null
//-------------------------------------------------------------------------
//-- Sample Use:
//~ var u = uniqueFileName (File ('~/Sample.txt' )) ;
//~ if (u != null) {
//~ //-- use the file here
//~ }
//-------------------------------------------------------------------------
//-- Written: 2010.05.02 by Jon S. Winters of electronic publishing support
//-- eps@electronicpublishingsupport.com
//-------------------------------------------------------------------------

//-- Do quick initial test. If the file is already unique then return it.
if (! fileRef.exists) {
return fileRef ;
}
//-- File isn't unique, get all the parts to construct a new one
var container = fileRef.parent ;
var baseName = fileRef.nameWithoutExtension() ;
var extension = fileRef.name.substr(baseName.length) ;

//-- Loop until reaching a unique file, then return it.
for (var version = 2; 99 >= version; version++) {
var uniqueTest = File (container + '/' + baseName + '_' + pad (version, 2, 0) + extension) ;
if (! uniqueTest.exists) {
return uniqueTest ;
}
}
//-- Unable to come up with a unique file, so return null
return null ;
}
//

No comments:

Post a Comment