Load And Save File Helper Functions

Audience Level

Beginner and above.

Introduction

These two JScript functions are simple helper functions to ease the process of saving and loading files via ADODB.Stream. They incorporate the added bonus of being able to do this using any of the native ADODB.Stream character sets such as “UTF-8” and “ISO-8859-1”, etc. The functions can be used within ASP, via the Windows Script Host (WScript) or the Console Script Host (CScript).

Source Code

/*
Function: doReadFile()
Description: Returns the contents of a file in the specified character set
Returns:
History:
20050128 1504GMT    v1      Andrew Urquhart     Created
*/

function doReadFile(strAbsoluteFilePath, strCharSet) {
    try {
        if (!strAbsoluteFilePath) {
            throw new Error(1, "Required parameter \"strAbsoluteFilePath\" was not defined");
        }
        if (!strCharSet) {
            throw new Error(2, "Required parameter \"strCharSet\" was not defined");
        }

        var strFileContents = "";
        var objStream       = new ActiveXObject("ADODB.Stream");
        objStream.Open();
        try {
            objStream.CharSet = strCharSet;
            objStream.LoadFromFile(strAbsoluteFilePath);
            strFileContents = objStream.ReadText(adReadAll);
        }
        catch (err) {
            throw new Error(err.number, "Loading failed:\r\n" + err.description);
        }
        finally {
            objStream.Close(); // Always close the stream regardless of what happens
        }
        return strFileContents;
    }
    catch (err) {
        throw new Error(err.number, "Function doReadFile() failed with parameters strAbsoluteFilePath=\"" + strAbsoluteFilePath + "\", strCharSet=\"" + strCharSet + "\". Message=\r\n" + err.description);
    }
}


/*
Function: doSaveFile()
Description: Saves the contents of a file in the specified character set
Returns:
History:
20050128 1512GMT    v1      Andrew Urquhart     Created
*/

function doSaveFile(strAbsoluteFilePath, strCharSet, strFileContents, blnOverwrite) {
    try {
        if (!strAbsoluteFilePath) {
            throw new Error(1, "Required parameter \"strAbsoluteFilePath\" was not defined");
        }
        if (!strCharSet) {
            throw new Error(2, "Required parameter \"strCharSet\" was not defined");
        }
        if (typeof strFileContents != "string") {
            throw new Error(3, "Required parameter \"strFileContents\" was not a string");
        }

        var objStream = new ActiveXObject("ADODB.Stream");
        objStream.Open();
        try {
            objStream.CharSet = strCharSet;
            objStream.WriteText(strFileContents);
            objStream.SaveToFile(strAbsoluteFilePath, (blnOverwrite ? adSaveCreateOverWrite : adSaveCreateNotExist));
            return true;
        }
        catch (err) {
            throw new Error(err.number, "SaveToFile failed:\r\n" + err.description);
        }
        finally {
            objStream.Close(); // Always close the stream regardless of what happens
        }
        return false;
    }
    catch (err) {
        throw new Error(err.number, "Function doSaveFile() failed with parameters strAbsoluteFilePath=\"" + strAbsoluteFilePath + "\", strCharSet=\"" + strCharSet + "\", strFileContents=\"" + strFileContents + "\", blnOverwrite=\"" + blnOverwrite + "\". Message=\r\n" + err.description);
    }
}

Download

Download the source directly.

Example Usage

var strContent  = "This is the contents I want to save to a file in UTF-8 format because it contains characters like äöüÄÖÜàùòìèé§çÑñ£$@” which don't fit inside the ASCII character set. If I used the Scripting.FileSystemObject COM object they'd be corrupted but they can be preserved by using the ADODB.Stream COM object instead.";
var strFilePath = Server.MapPath("/myfolder/myfile.txt");

try {
    doSaveFile(strFilePath, "UTF-8", strContent, true);
}
catch (err) {
    Response.Write("The file could not be saved to path \"" + Server.HTMLEncode(strFilePath) + "\" because error \"" + err.number + "\" occurred with message: " + err.description);
}

Notes

If you encounter syntax errors with the ADO constants in your ASP pages (i.e. “adSaveCreateOverWrite”) then you need to add the ADODB Metadata Type library declaration to the top of your “global.asa”, e.g.:

<!--METADATA NAME="Microsoft ActiveX Data Objects 2.5 Library" TYPE="TypeLib" UUID="{00000205-0000-0010-8000-00AA006D2EA4}"-->

In non-ASP environments you'll likely have to declare and assign the ADO constants yourself as ordinary variables inside your application — you can determine the numeric values of the ‘constants’ by inspecting the contents of an “adojs.inc” or “adovbs.inc” file. In WScript and CScript environments you may be able to utilise the “Package” functionality to import the meta-type library into your Windows Script application.

Advertisement

Feedback

Voting Panel
Is this useful?
or
Did you find any bugs?
or
Did it solve your programming problem?
or
Rate this script: (0=poor, 5=very good)
Answers are anonymous, only the combined totals are stored. Uses cookies.