M0194 Web-based Programming Lanjut Session 4 

advertisement
M0194
Web-based Programming Lanjut
Session 4
 2004 Tau Yenny, SI - Binus
2
The Scripting Runtime Library Objects



Scripting Objects
Scripting.Dictionary Object
Scripting.FileSystemObject Object




Drive Object
Folder Object
File Object
Scripting.TextStream Object
 2004 Tau Yenny, SI - Binus
3
Scripting Objects

Scripting languages have an object model.



The model is for the objects that the scripting language
provide
As opposed to the objects like Request and Response that
are provided directly by the ASP DLL
The scripting objects are provided by the Microsoft
Scripting Runtime Library (scrrun.dll), which
installed with the default Active Scripting script
engine.
 2004 Tau Yenny, SI - Binus
4
Different Types of Objects and
Components


‘Object’ and ‘component’ are all accessible in the
same way - through COM.
Conceptually, can be divided into 4 groups:




Intrinsic ASP objects such as ObjectContext, Request,
Response, Application, Session, Server and ASPError.
Scripting objects that are made available through the
Scripting Runtime Library. These are Dictionary, FileSystem
and TextStream.
Installable components are those provided by Microsoft
in a standard installation of IIS 5.0 and ASP 3.0.
Other components that we either buy from independent
vendors, find on the Web, or create ourselves.
 2004 Tau Yenny, SI - Binus
5
The VBScript and JScript Scripting
Objects

Microsoft provides 3 main objects as part of the Scripting Runtime
Library:
 The Dictionary object provides a useful storage object that we can
use to storage values, accessed and referenced by their name
rather than by index. For example, it’s ideal for storing the
name/value pairs that we retrieve from the ASP Request object.

The FileSystemObject object provides us with access to the
underlying file system on the server. We can use FileSystemObject
object to iterate through the machine’s local and networked drives,
folders and files.

The TextStream object provides access to files stored on disk, and
is used in conjunction with the FileSystemObject. It can read from or
write to text (sequential) files. It can only be instantiated via the
FileSystemObject object, so you might prefer to think of it as a child
of that object.
 2004 Tau Yenny, SI - Binus
6
The VBScript and JScript Scripting
Objects
Scripting Run-time
TextStream Object
FileSystemObject Object
Drives Collection
Dictionary Object
Drive Object
Folders Collection
FileSystemObject object acts as ‘parent’ for
a series of other objects and collection that
we use to interact with the file system.
Folder Object
Files Collection
File Object
 2004 Tau Yenny, SI - Binus
7
Creating Instances of Objects and
Components

Using the Server.CreateObject Method
<%
Dim objThis
Set objThis = Server.CreateObject(“ADODB.Connection”)
%>

Using the <OBJECT> element
<OBJECT ID = “objThis” RUNAT=“SERVER” PROGID=“This.Object”>
<PARAM NAME=“param1” VALUE=“value1”>
<PARAM NAME=“param2” VALUE=“value2”>
</OBJECT>
 2004 Tau Yenny, SI - Binus
8
Creating Instances of Objects and
Components

Specifying a ClassID
<OBJECT ID = “objThis” RUNAT=“SERVER”
CLASSID=“clsid:892D6DA7-E0F9-11D2-B2E9-00105A42AF30”>
<PARAM NAME=“param1” VALUE=“value1”>
<PARAM NAME=“param2” VALUE=“value2”>
</OBJECT>
When we come to instantiating objects on our own server, we should be
aware of what actually is installed in the way of objects and components.
So when we create instances of objects in our ASP code, we can safely use
the PROGID string.
This is why the ClassID is rarely used in ASP pages.
 2004 Tau Yenny, SI - Binus
9
Creating Instances of Objects and
Components

Setting the Scope of Object Instances



By default, all object and component instances have page scope. This
means that they exist only as long as the page is executing in ASP.
If we place the <OBJECT> declaration in the global.asa file that exists in
the root directory of our Web site or virtual application, we can specify
that an object or component should have application or session scope
instead.
Creating objects with Application-Level Scope
<OBJECT ID = “objThis” RUNAT=“SERVER” PROGID=“This.Object”
SCOPE=“APPLICATION” >
</OBJECT>

Creating objects with Session-Level Scope
<OBJECT ID = “objThis” RUNAT=“SERVER” PROGID=“This.Object”
SCOPE=“SESSION” >
</OBJECT>
 2004 Tau Yenny, SI - Binus
10
Creating Instances of Objects and
Components
The Difference between Server.CreateObject &
<OBJECT>

Server.CreateObject



creates an instance of the object immediately.
can remove objects from a Session or Application
The <OBJECT> element


only creates an instance of the object it specifies when we
first reference that object. So if we stop using the objectin
our code, it won’t get created.
cannot remove objects from a Session or Application if
they were created using <OBJECT>
 2004 Tau Yenny, SI - Binus
11
The Scripting.Dictionary Object

Many Microsoft languages provide collections. We
can think a collection as being like an array, but we
don’t have to worry about which row or column the
data is in, we just access it using a unique key.

VBScript and JScript both offer a similar object with
the collection, known as the Scripting Dictionary
(or just Dictionary) object. This acts like a twodimensional array, holding the key and the related
item of data together.
 2004 Tau Yenny, SI - Binus
12
Creating and Using Dictionary
Objects
‘ In VBScript
Dim objMyData
Set objMyData = Server.CreateObject(“Scripting.Dictionary”)
// In JSCript
var objMyData = Server.CreateObject(“Scripting.Dictionary”)
<!-- Server-side with an OBJECT element -->
<OBJECT ID = “objMyData” RUNAT=“SERVER” SCOPE=“PAGE”
PROGID=“Scripting.Dictionary” >
</OBJECT>
The Dictionary object can also be used client-side in Internet Explorer.
 2004 Tau Yenny, SI - Binus
13
The Dictionary Object Members
Summary
The Dictionary Object’s Properties
Property
Description
CompareMode
(VBScript only). Sets or returns the string comparison mode for
the keys.
Count
Read only. Returns the number of key/item pairs in the Dictionary.
Item (key)
Sets or returns the value of the item for the specified key.
Key (key)
Sets the value of a key.
The Dictionary Object’s Methods
Method
Description
Add (key, item)
Adds the key/item pair to the Dictionary.
Exists (key)
Returns True if the specified key exists or False if not.
Items ( )
Returns an array containing all the items in a Dictionary object.
Keys ( )
Returns an array containing all the keys in a Dictionary object.
Remove (key)
Removes a single key/item pair specified by key.
RemoveAll ( )
Removes all the key/item pairs.
 2004 Tau Yenny, SI - Binus
14
Adding Items To and Removing Items
From a Dictionary
‘In VBScript :
objMyData.Add “MyKey”, “MyItem”
objMyData.Add “YourKey”, “YourItem”
blnIsThere = objMyData.Exists(“MyKey”)
StrItem = objMyData.Item(“YourKey”)
StrItem = objMyData.Remove(“MyKey”)
objMyData.RemoveAll
‘Add value MyItem with key MyKey
‘Add value YourItem with key YourKey
‘Returns True because the item exists
‘Retrieve value of YourKey
‘Retrieve and remove Mykey
‘Remove all the items
// In JScript :
objMyData.Add (‘MyKey’, ‘MyItem’);
‘Add value MyItem with key MyKey
objMyData.Add (‘YourKey’, ‘YourItem’);
‘Add value YourItem with key YourKey
var blnIsThere = objMyData.Exists(‘MyKey’); ‘Returns True because the item exists
var StrItem = objMyData.Item(‘YourKey’);
‘Retrieve value of YourKey
var StrItem = objMyData.Remove(‘MyKey’); ‘Retrieve and remove Mykey
objMyData.RemoveAll();
‘Remove all the items
 2004 Tau Yenny, SI - Binus
15
Changing the Value of a Key or Item
To change the value of the item with the key MyKey, we use :
objMyData.Item(“MyKey”) = “NewValue”
‘ in VBScript
objMyData.Item(‘MyKey’) = ‘NewValue’;
// in JScript
If the key we specified isn’t found in the Dictionary, a new key/item pair is created
with the key as MyKey and the item value as NewValue.
If we try to retrieve an item using a key that doesn’t exists, we not only get an
empty string as the result (as we’d expect) but also a new key/item pair is added
to the Dictionary. This has the key we specified, but with the item value left
empty.
To change the value of a key, without changing the value of the corresponding
item, we use the Key property. If the specified key isn’t found, a Runtime error is
generated.
objMyData.Key(“MyKey”) = “MyNewKey”
‘ in VBScript
objMyData.Key(‘MyKey’) = ‘MyNewKey’;
// in JScript
 2004 Tau Yenny, SI - Binus
16
Iterating Through a Dictionary
‘In VBScript :
arrKeys = objMyData.Keys
arrItems = objMyData.Items
‘Get all the keys into array
‘Get all the items into array
For intLoop = 0 To objMyData.Count -1 ‘Iterate through the array
strThisKey = arrKeys(intLoop)
‘This is the key value
strThisItem = arrItems(intLoop)
‘This is the item (data) value
Next
// In JScript :
// Get VB-style arrays using the Keys() and Items() method
var arrKeys = new VBArray (objMyData.Keys()).toArray();
var arrItems = new VBArray (objMyData.Items()).toArray();
for (intLoop = 0; intLoop< objMyData.Count ; intLoop++) { // Iterate through the array
strThisKey = arrKeys[intLoop];
// This is the key value
strThisItem = arrItems[intLoop];
// This is the item (data) value
}
 2004 Tau Yenny, SI - Binus
17
Iterating Through a Dictionary

Alternatively in VBScript, we can use For Each… Next
construct to do the same:
‘ Iterate the Dictionary as a collection in VBScript
For Each objItem in arrItems
Response.Write objItem & “ = “ & arrItems(objItem) & “<BR>”
Next
 2004 Tau Yenny, SI - Binus
18
The Scripting.FileSystemObject Object

The FileSystemObject object
 provides access to the computer’s file system
 allowing us to manipulate text files, folders and drives
 Available in VBScript and JScript for use in ASP pages on the
server.
 Can also be used client-side in IE 5
 providing that the pages have the .hta file extension, to indicate
that they are part of a Hypertext Application (HTA).

A Hypertext Application is made up of a special ‘trusted’ pages
that contain the <HTA:APPLICATION> element in the <HEAD>
section of the page, for example:
<HTA:APPLICATION ID=“objMyApp” APPLICATIONNAME=“myAPP”>
 2004 Tau Yenny, SI - Binus
19
The Scripting.FileSystemObject Object
We can create an instance of the FileSystemObject object using:
‘ In VBScript
Dim objMyFSO
Set objMyFSO = Server.CreateObject(“Scripting.FileSystemObject”)
// In JSCript
var objMyFSO = Server.CreateObject(“Scripting.FileSystemObject”)
<!-- Server-side with an OBJECT element -->
<OBJECT ID = “objFSO” RUNAT=“SERVER” SCOPE=“PAGE”
PROGID=“Scripting.FileSystemObject” >
</OBJECT>
The type library for the complete scripting Runtime library can be added to any
ASP page using:
<!-- METADATA TYPE=“typelib” FILE=“C:\WinNT\System32\scrrun.dll” -->
 2004 Tau Yenny, SI - Binus
20
The Scripting.FileSystemObject Members
Summary
The FileSystemObject’s Property
Property
Drives
Description
Returns the collection of Drive objects that are available from the local
machine. This includes network drives that are mapped from this machine.
The FileSystemObject’s Methods for Working with Drives
Method
Description
DriveExists
(drivespec)
Returns True if the drive specified in drivespec exists, or False if not.
The drivespec parameter can be a drive letter as a string or a full
absolute path for a folder or file.
GetDrive
(drivespec)
Returns a Drive object corresponding to the drive specified in
drivespec. The format for drivespec can include the colon, path
separator or be a network share, i.e. “c”, “c:”, ”c:\” or
“\\machine\sharename”
GetDriveName
(drivespec)
Return the name of the drive specified in drivespec as a string. The
drivespec parameter must be an absolute path to a file or folder, or
just the drive letter such as “c:” or just “c”.
 2004 Tau Yenny, SI - Binus
21
The Scripting.FileSystemObject Members
Summary
The FileSystemObject’s Methods for Working with Folders
Method
Description
BuildPath
(path, name)
Adds the file or folder specified in name to the existing path, adding a
path separator character (‘\’) if required.
CopyFolder
(source,
destination,
overwrite)
Copies the folder (s) specified in source (wildcards can be included) to
the folder specified in destination, including all the files contained in
the source folder(s). If source contains wildcards or destination ends
with a path separator character (‘\’), then destination is assumed to
be a folder into which the copied folder(s) will be placed. Otherwise it
is assumed to be a full path and name for a new folder to be created.
An error will occur if the destination folder already exists and the
optional overwrite parameter is set to False. The default for
overwrite is True.
CreateFolder
(foldername)
Creates a new folder which has the path and name specified in
foldername. An error occurs if the specified folder already exists.
 2004 Tau Yenny, SI - Binus
22
The Scripting.FileSystemObject Members
Summary
Method
Description
DeleteFolder
(folderspec, force)
Deletes the folder or folders specified in folderspec (wildcards
can be included in the final component of the path) together
with all their contents. If the optional force parameter is set to
True, the folders will be deleted even if their read-only attribute
(or that any contained files) is set. The default for force is
False.
FolderExists
(folderspec)
Returns True if the folder specified in folderspec exists, or
False if not. The folderspec parameter can contain an
absolute or relative path for the folder, or just the folder name to
look in the current folder.
GetAbsolutePathName
(pathspec)
Takes a path that unambiguously identifies a folder and, taking
into account the current folder’s path, returns a full path
specification for the pathspec folder. For example, if the
current folder is “c:\docs\sales\” and pathspec is “jan”, the
returned value is “c:\docs\sales\jan”. Wildcards and the “..”
and “\\” path operators are accepted.
 2004 Tau Yenny, SI - Binus
23
The Scripting.FileSystemObject Members
Summary
Method
Description
GetFolder
(folderspec)
Returns a Folder object corresponding to the folder specified in
folderspec. This can be a relative or absolute path to the required
folder.
GetParentFolder
(pathspec)
Returns the name of the parent folder of the file or folder specified in
pathspec. Doesn’t check for existence of the folder.
GetSpecialFolder
(folderspec)
Returns a Folder object corresponding to 1 of the special Windows
folders. The permissible values for folderspec are WindowsFolder (0),
SystemFolder (1) and TemporaryFolder (2).
MoveFolder
(source,
destionation)
Moves the folder or folders specified in source to the folder specified in
destination. Wildcards can be included in source, but not in
destination. If source contains wildcards or destination ends with a
path separator character (‘\’) then destination is assumed to be the
folder in which to place the moved folders. Otherwise it is assumed to
be a full path and name for a new folder. An error will occur if the
destination folder already exists.
 2004 Tau Yenny, SI - Binus
24
The Scripting.FileSystemObject Members
Summary
The FileSystemObject’s Methods for Working with Files
Method
Description
CopyFile
(source,
destination,
overwrite)
Copies the file or files specified in source (wildcards can be included) to
the folder specified in destination. If source contains wildcards or
destination ends with a path separator character (‘\’), then destination
is assumed to be a folder. Otherwise is assumed to be a full path and
name for the new file. An error will occur if the destination file already
exists and the optional overwrite parameter is set to False. The default
for overwrite is True.
CreateTextFile
(filename,
overwrite,
unicode)
Creates a new text file on disk with the specified filename, and returns
a TextStream object that refers to it. If the optional overwrite parameter
is set to True, any existing file with the same path and name will be
overwritten. The default for for overwrite is False. If the optional
unicode parameter is set to True, the content of the file will be stored
as Unicode text. The default for unicode is False.
DeleteFile
(filespec,
force)
Deletes the file or files specified in filespec (wildcards can be included).
If the optional force parameter is set to True, the file(s) will be deleted
even if the Read-only attribute is set. The default for force is False.
 2004 Tau Yenny, SI - Binus
25
The Scripting.FileSystemObject Members
Summary
Method
Description
FileExists
(filespec)
Returns True if the file specified in filespec exists, or False if not.
The filespec parameter can contain an absolute or relative path for
the file, or just the filename to look in the current folder.
GetBaseName
(filespec)
Returns just the name of a file specified in filespec, i.e. with the path
and file extension removed
GetExtensionName Returns just the file extension of a file specified in filespec, i.e. with
(filespec)
the path and filename removed.
GetFile (filespec)
Returns a File object corresponding to the file specified in filespec.
This can be a relative or absolute path to the required file.
GetFileName
(pathspec)
Returns the name part of the path and filename specified in
pathspec, or the last folder name of there is no file name. Doesn’t
check for existence of the file or folder.
GetTempName ( )
Returns a randomly generated file name, which can be used for
performing operations that require a temporary file or folder.
 2004 Tau Yenny, SI - Binus
26
The Scripting.FileSystemObject Members
Summary
Method
Description
MoveFile (source,
destination)
Moves the file or files specified in source to the folder specified in
destination. Wildcards can be included in source but not in
destination. If source contains wildcards or destination ends with
path separator character (‘\’), then destination is assumed to be a
folder. Otherwise it is assumed to be a full path and name for the
new file. An error will be occur if the destination file already exists.
OpenTextFile
(filename,
iomode, create,
format)
Creates a file named filename, or opens an existing file named
filename, and returns a TextStream object that refers to it. The
filename parameter can contain an absolute or relative path. The
iomode parameter specifies the type of access required. The
permissible values are ForReading(1 –the default), ForWriting (2),
and ForAppending (8). If the create parameter is set to True when
writing or appending to file that doesn’t exists, a new file will be
created. The default for create is False. The format parameter
specifies the format of the data to be read from or written to the file.
Permissible values are TristateFalse (0-default) to open it as ASCII,
TristateTrue (-1) to open it as Unicode, and TristateUseDefault (-2)
to open it using the system default format.
 2004 Tau Yenny, SI - Binus
27
Working with Drives
Get a list of available drive letters using the DriveExists method.
‘ In VBScript
Response.Write "<H1>Using the DriveExists Method<HR></H1>“
Set objFSO = Server.CreateObject(“Scripting.FileSystemObject”)
For intCode=65 To 90
‘ANSI Codes for ‘A’ to ‘Z’
strLetter = Chr(intCode)
If objFSO.DriveExists(strLetter) Then
Response.Write “Found drive “ & strLetter & “ : <BR>”
End If
Next
 2004 Tau Yenny, SI - Binus
28
The Drive Object
Property
Description
AvailableSpace
Returns the amount of space available to this user on the drive, taking into
account quotas and/or other restrictions.
DriveLetter
Returns the drive letter of the drive.
DriveType
Returns the type of the drive. The values are Unknown (0), Removable (1),
Fixed (2), Network (3), CDRom (4), and RamDisk (5). However, note that
the current version of scrrun.dll does not include the pre-defined constant
for Network, so you may have to use the decimal value 3 instead.
FileSystem
Returns the type of file system for the drive. The values include “FAT”,
“NTFS”, and “CDFS”
FreeSpace
Returns the actual total amount of free space available on the drive.
IsReady
Returns a Boolean value indicating if the drive is ready (True) or not (False).
Path
Returns the path for the drive as a drive letter and colon, i.e. “C:”.
RootFolder
Returns a Folder object representing the root folder of the drive.
SerialNumber
Returns a decimal serial number used to uniquely identify a disk volume.
ShareName
Returns the network share name for the drive if it is a networked drive.
TotalSize
Returns the total size (in bytes) of the drive.
VolumeName
Sets or returns the volume name of the drive if it is a local drive.
 2004 Tau Yenny, SI - Binus
29
The Drive Object
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
<%
'In VBScript:
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
Set colDrives = objFSO.Drives
'Create a Drives collection
Response.Write "<H1>Using the Drives Collection<HR></H1>"
For Each objDrive in colDrives
'Iterate through the Drives collection
Response.Write "DriveLetter : " & objDrive.DriveLetter & "<BR>"
Response.Write "DriveType : " & objDrive.DriveType
If objDrive.DriveType = 3 Then
If objDrive.IsReady Then
Response.Write "Remote drive with ShareName: <B>" & objDrive.ShareName & "</B><BR>"
Else
Response.Write "Remote drive - IsReady property returned False<BR>"
End If
Else
Response.Write "FileSystem: <B>" & objDrive.FileSystem & "</B>, "
Response.Write "SerialNumber: <B>" & objDrive.SerialNumber & "</B><BR> "
Response.Write "Local drive with VolumeName: <B>" & objDrive.VolumeName & "</B>, "
Response.Write "AvailableSpace: <B>" & objDrive.AvailableSpace & "</B> bytes, "
Response.Write "FreeSpace: <B>" & objDrive.FreeSpace & "</B> bytes, "
Response.Write "TotalSize: <B>" & objDrive.TotalSize & "</B> bytes<BR><BR>"
End If
Next
%>
 2004 Tau Yenny, SI - Binus
30
The Drive Object
If you don’t have a disk in your A: drive or CD-ROM drive, you’ll get a ‘Disk Not Ready’ error
 2004 Tau Yenny, SI - Binus
31
The Folder Object
The RootFolder property of the Drive object returns a Folder object
Property
Description
Attributes
Returns the attributes of the folder. Can be a combination of any of the
following values: Normal (0), ReadOnly (1), Hidden (2), System (4),
Volume (name) (8), Directory (folder) (16), Archive (32), Alias (64)
and Compressed (128). For Example, a hidden read-only file would
have the value 3.
DateCreated
Returns the date and time that the folder was created.
DateLastAccessed
Returns the date and time that the folder was last access.
DateLastModified
Returns the date and time that the folder was last modified.
Drive
Returns the drive letter of the drive on which the folder resides.
Files
Returns a Files collection containing File objects representing all the
files within this folder.
IsRootFolder
Returns a Boolean value indicating if the folder is the root folder of the
current drive.
Name
Sets or returns the name of the folder.
ParentFolder
Returns the Folder object for the parent folder of this folder.
 2004 Tau Yenny, SI - Binus
32
The Folder Object
Property
Description
Path
Returns the absolute path of the folder, using long file names where appropriate.
ShortName
Returns the DOS-style 8.3 version of the folder name.
ShortPath
Returns the DOS-style 8.3 version of the absolute path of this folder.
Size
Returns the size of all files and subfolders contained in the folder.
SubFolders
Returns a Folders collection consisting of all folders contained in the folder,
including hidden and system folders.
Type
Returns a string that is a description of the folder type (such as “Recycle Bin”) if
available.
Methods
Copy
(destination,
overwrite)
Description
Copies this folder and all its contents to the folder specified in destination. If
destination ends with a path separator character (‘\’) then destination is
assumed to be a folder into which the copied folder will be placed. Otherwise,
it is assumed to be a full path and name for a new folder to be created. An
error will occur if the destination folder already exists, and the optional
overwrite parameter is set to False. The default for overwrite is True.
 2004 Tau Yenny, SI - Binus
33
The Folder Object
Method
Description
Delete (force)
Deletes this folder and all its contents. If the optional force parameter is
set to True the folder will be deleted, even if the Read-only attribute is
set on it or any contained files. The default for force is False.
Move
(destination)
Moves this folder and all its contents to the folder specified in
destination. If destination ends with a path separator character (‘\’)
then destination is assumed to be a folder in which to place the moved
folder. Otherwise, it is assumed to be a full path and name for a new
folder. An error will occur if the destination folder already exists.
CreateTextFile
(filename,
overwrite,
unicode)
Creates a new text file within this folder with the specified filename,
and returns a TextStream object that refers to it. If the optional
overwrite parameter is set to True, any existing file with the same
name will be overwritten. The default for overwrite is False. If the
optional unicode parameter is set to True, the content of the file will be
stored as unicode text. The default for unicode is False.
 2004 Tau Yenny, SI - Binus
34
The Folder Object
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
<%
'In VBScript
Response.Write "<H1>Using the Folders Collection<HR></H1>"
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
Set objDriveC = objFSO.GetDrive("C:")
'get a reference to drive C
Set objRoot = objDriveC.RootFolder
'get a reference to the root folder
Set colFolders = objRoot.SubFolders
‘get a reference to the Folders collection
For Each objFolder in colFolders
Response.Write "Name: " & objFolder.Name & "   "
Response.Write "ShortName: " & objFolder.ShortName & "  "
Response.Write "Type: " & objFolder.Type & "<BR>"
Response.Write "Path: " & objFolder.Path & "  "
Response.Write "ShortPath: " & objFolder.ShortPath & "<BR>"
Response.Write "Created: " & objFolder.DateCreated & "  "
Response.Write "LastModified: " & objFolder.DateLastModified & "<P>"
Next
%>
 2004 Tau Yenny, SI - Binus
35
The Folder Object
 2004 Tau Yenny, SI - Binus
36
The Folder Object

Working with Special Folders
GetSpecialFolder method returns the Folder object for any of three
‘special folders’ on the machine:



WindowsFolder – the %Windows% directory, by default WinNT (or
Windows on a non-NT/2000 machine)
SystemFolder – the %System% directory, by default WinNT\System32
(or Windows\System on a non-NT/2000 machine)
TemporaryFolder – the %Temp% directory, by default WinNT\Temp (or
Windows\Temp on a non-NT/2000 machine)
 2004 Tau Yenny, SI - Binus
37
The Folder Object
3.
<%
'In VBScript
Response.Write "<H1>Using the SpecialFolders Method<HR></H1>"
4.
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
5.
Set objFolder = objFSO.GetSpecialFolder(WindowsFolder)
Response.Write "GetSpecialFolder(WindowsFolder) returned:<BR>"
Response.Write "Path: " & objFolder.Path & "<BR>"
Response.Write "Type: " & objFolder.Type & "<P>"
1.
2.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
Set objFolder = objFSO.GetSpecialFolder(SystemFolder)
Response.Write "GetSpecialFolder(SystemFolder) returned:<BR>"
Response.Write "Path: " & objFolder.Path & "<BR>"
Response.Write "Type: " & objFolder.Type & "<P>"
Set objFolder = objFSO.GetSpecialFolder(TemporaryFolder)
Response.Write "GetSpecialFolder(TemporaryFolder) returned:<BR>"
Response.Write "Path: " & objFolder.Path & "<BR>"
Response.Write "Type: " & objFolder.Type & "<P>"
%>
 2004 Tau Yenny, SI - Binus
38
The Folder Object
 2004 Tau Yenny, SI - Binus
39
The File Object


Provides access to the properties of file, and implements methods to
manipulate that file.
Each Folder object exposes a Files collection, containing File
objects that correspond to the files in that folder
Property
Description
Attributes
Returns the attributes of the file. Can be a combination of any of
the following values: Normal (0), ReadOnly (1), Hidden (2),
System (4), Volume (name) (8), Directory (folder) (16), Archive
(32), Alias (64) and Compressed (128).
DateCreated
Returns the date and time that the file was created.
DateLastAccessed
Returns the date and time that the file was last access.
DateLastModified
Returns the date and time that the file was last modified.
Drive
Returns a drive object representing the drive on which the file
resides.
Name
Sets or returns the name of the file.
 2004 Tau Yenny, SI - Binus
40
The File Object
Property
Description
ParentFolder Returns the Folder object for the parent folder of this file.
Path
Returns the absolute path of the file, using long file names where appropriate.
ShortName
Returns the DOS-style 8.3 version of the file name.
ShortPath
Returns the DOS-style 8.3 version of the absolute path of this file.
Size
Returns the size of all the file in bytes
Type
Returns a string that is a description of the file type (such as “Text Document”
for a .txt file) if available.
Method
Copy (destination,
overwrite)
Description
Copies this file to the folder specified in destination. If destination
ends with a path separator character (‘\’) then destination is
assumed to be a folder into which the copied file will be placed.
Otherwise, it is assumed to be a full path and name for a new folder
to be created. An error will occur if the destination file already exists,
and the optional overwrite parameter is set to False. The default for
overwrite is True.
 2004 Tau Yenny, SI - Binus
41
The File Object
Method
Description
Delete (force)
Deletes this file. If the optional force parameter is set to True the file will be
deleted, even if the Read-only attribute is set. The default for force is False.
Move (destination)
Moves this file to the folder specified in destination. If destination ends
with a path separator character (‘\’) then destination is assumed to be a
folder in which to place the moved file. Otherwise, it is assumed to be a full
path and name for a new file. An error will occur if the destination file
already exists.
CreateTextFile
(filename,
overwrite, unicode)
Creates a new text file within this folder with the specified filename, and
returns a TextStream object that refers to it. If the optional overwrite
parameter is set to True, any existing file with the same path and name will
be overwritten. The default for overwrite is False. If the optional unicode
parameter is set to True, the content of the file will be stored as unicode
text. The default for unicode is False.
OpenAsTextStream
(iomode, format)
Opens a specified file and returns a TextStream object that can be used to
read from, write to, or append to the file. The iomode parameter specifies
the type of access required. The permissible values are ForReading (1- the
default), ForWriting (2), and ForAppending (8). The format parameter
specifies the format of the data to be read from or written to the file.
Permissible values are TristateFalse (0 - the default) to open it as ASCII,
TristateTrue (-1) to open it as Unicode, and TristateUseDefault (-2) to
open it using the system default format.
 2004 Tau Yenny, SI - Binus
42
The File Object
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
<% 'In VBScript
Response.Write "<H1>Using the Files Collection<HR></H1>"
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
Set objDriveC = objFSO.GetDrive("C:")
'get a reference to drive C
Set objRoot = objDriveC.RootFolder
'get a reference to the root folder
Set objFolders = objRoot.SubFolders
' get a reference to the Folders collection
'get a reference to the first folder in the SubFolders collection
For Each objFolder In objFolders
Set objFolder1 = objFolders.Item((objFolder.Name))
Exit For
Next
For Each objFile in objFolder1.Files
Response.Write "Name: " & objFile.Name & "   "
Response.Write "ShortName: " & objFile.ShortName & "  "
Response.Write "Size: " & objFile.Size & "<BR>"
Response.Write "Type: " & objFile.Type & "<BR>"
Response.Write "Path: " & objFile.Path & "  "
Response.Write "ShortPath: " & objFile.ShortPath & "<BR>"
Response.Write "Created: " & objFile.DateCreated & "  "
Response.Write "LastModified: " & objFile.DateLastModified & "<P>"
Next
%>
 2004 Tau Yenny, SI - Binus
43
The File Object
 2004 Tau Yenny, SI - Binus
44
The Scripting.TextStream Object

Methods for creating TextStream Object



CreateTextFile (filename, overwrite, unicode)
OpenTextFile (filename, iomode, create, format)
OpenAsTextStream (iomode, format)
Method
FileSystemObject
object
Folder object
File object
CreateTextFile
Yes
Yes
Yes
OpenTextFile
Yes
(No)
(No)
OpenAsTextStream
(No)
(No)
Yes
 2004 Tau Yenny, SI - Binus
45
The Scripting.TextStream Object

Creating New Text Files
‘In VBScript
Set objFSO = Server.CreateObject(“Scripting.FileSystemObject”)
Set objTStream = objFSO.CreateTextFile(“C:\TextFiles\MyFile.txt”, True, False)
‘In JScript
var objFSO = Server.CreateObject(‘Scripting.FileSystemObject’);
var objTStream = objFSO.CreateTextFile(‘C:\TextFiles\MyFile.txt’, True, False);
Once the file has been created, we can use the objTStream reference to
work with the file.
 2004 Tau Yenny, SI - Binus
46
The Scripting.TextStream Object

Opening Existing Text Files
‘In VBScript
Set objFSO = Server.CreateObject(“Scripting.FileSystemObject”)
Set objTStream = objFSO.OpenTextFile(“C:\TextFiles\MyFile.txt”, ForReading)
‘In JScript
var objFSO = Server.CreateObject(‘Scripting.FileSystemObject’);
var objTStream = objFSO.OpenTextFile(‘C:\TextFiles\MyFile.txt’);

To open file for writing, and create a new file if the one
specified doesn’t exists
‘In VBScript
Set objTStream = objFSO.OpenTextFile(“C:\TextFiles\MyFile.txt”, ForWriting, True)
‘In JScript
var objTStream = objFSO.OpenTextFile(‘C:\TextFiles\MyFile.txt’, ForWriting, true);
 2004 Tau Yenny, SI - Binus
47
The Scripting.TextStream Object

Opening Existing Unicode File ready to append data to it, but
not create a new file if the one specified doesn’t already
exists
‘In VBScript
Set objTStream = objFSO.OpenTextFile(“C:\TextFiles\MyFile.txt”, ForAppending, _
False, TristateTrue)
‘In JScript
var objTStream = objFSO.OpenTextFile(‘C:\TextFiles\MyFile.txt’, ForAppending, _
false, true);
 2004 Tau Yenny, SI - Binus
48
The Scripting.TextStream Object

Opening a File Object as a TextStream Object
‘In VBScript
Set objTStream = objFileObject.OpenAsTextStream(ForAppending, False)
‘In JScript
var objTStream = objFileObject.OpenTextFile(ForAppending, false);

To start with a new empty file
‘In VBScript
Set objTStream = objFileObject.OpenAsTextStream(ForWriting)
‘In JScript
var objTStream = objFileObject.OpenTextFile(ForWriting);

To read from the file
‘In VBScript
Set objTStream = objFileObject.OpenAsTextStream(ForReading)
‘In JScript
var objTStream = objFileObject.OpenTextFile(ForReading);
 2004 Tau Yenny, SI - Binus
49
The Scripting.TextStream Object
Property
Description
AtEndOfLine
Returns True if the file pointer is at the end of a line in the file.
AtEndOfStream
Returns True if the file pointer is at the end of the file.
Column
Returns the column number of the current character in the file,
starting from 1.
Line
Returns the current line number in the file, starting from 1.
All the properties are read-only.
The AtEndOfLine and AtEndOfStream are only available for a file that is
opened with iomode of ForReading. Referring to them otherwise causes an
error to occur.
 2004 Tau Yenny, SI - Binus
50
The Scripting.TextStream Object
Method
Description
Close ( )
Closes an open file.
Read (numchars)
Reads numchars characters from the file.
ReadAll ( )
Reads the entire file as a single string.
ReadLine ( )
Reads a line (up to a carriage return and line feed) from the file as
a string.
Skip (numchars)
Skips and discards numchars characters when reading from the
file.
SkipLine ( )
Skips and discards the next line when reading from the file.
Write (string)
Writes string to the file.
WriteLine (string)
Writes string (optional) and a new line character to the file.
WriteBlankLines (n)
Writes n new line characters to the file.
 2004 Tau Yenny, SI - Binus
51
The Scripting.TextStream Object
Writing to a Text File
‘ In VBScript
objTStream.WriteLine “At last I can create files with VBScript!”
objTStream.WriteLine
objTStream.WriteLine “Here are three blank lines : “
objTStream.WriteBlankLines 3
objTStream.Write “… and this is “
objTStream.WriteLine “the last line.”
objTStream.Close
// In JScript
objTStream.WriteLine (‘At last I can create files with JScript!’);
objTStream.WriteLine ();
objTStream.WriteLine (‘Here are three blank lines : ‘);
objTStream.WriteBlankLines (3);
objTStream.Write (‘… and this is ‘);
objTStream.WriteLine (‘the last line.’);
objTStream.Close();
 2004 Tau Yenny, SI - Binus
52
The Scripting.TextStream Object
Reading from a Text File
‘ In VBScript
Do While Not objTStream.AtEndOfStream
intLineNum = objTSTream.Line
‘get the line number
strLineNum = Right(“000” & CStr(intLineNum), 4) ‘format it as a 4-character
strLineText = objTStream.ReadLine
Response.Write strLineNum & “ : “ & strLineText & “<BR>”
Loop
objTStream.Close
// In JScript
while (! objTStream.AtEndOfStream) {
intLineNum = objTSTream.Line;
‘get the line number
strLineNum = ‘000’ + intLineNum.toString(); ‘format and convert to a string
strLineNum = substr(strLineNum, strLineNum.length – 4, 4);
strLineText = objTStream.ReadLine();
Response.Write (strLineNum + ‘ : ‘ + strLineText & <BR>’);
}
objTStream.Close();
 2004 Tau Yenny, SI - Binus
Download