Web-based Programming Lanjut Pertemuan 4

1 Web-based Programming Lanjut Pertemuan 4Matakuliah : M0...
Author: Todd Wilkins
0 downloads 0 Views

1 Web-based Programming Lanjut Pertemuan 4Matakuliah : M0492 / Web-based Programming Lanjut Tahun : 2007 Web-based Programming Lanjut Pertemuan 4

2 The Scripting Runtime Library ObjectsScripting Objects Scripting.Dictionary Object Scripting.FileSystemObject Object Drive Object Folder Object File Object Scripting.TextStream Object Bina Nusantara

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. Bina Nusantara

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. Bina Nusantara

5 The VBScript and JScript Scripting ObjectsMicrosoft 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. Bina Nusantara

6 The VBScript and JScript Scripting ObjectsScripting Run-time TextStream Object Dictionary Object FileSystemObject Object Drives Collection Drive Object Folders Collection Folder Object Files Collection File Object FileSystemObject object acts as ‘parent’ for a series of other objects and collection that we use to interact with the file system. Bina Nusantara

7 Creating Instances of Objects and ComponentsUsing the Server.CreateObject Method Using the element <% Dim objThis Set objThis = Server.CreateObject(“ADODB.Connection”) %> Bina Nusantara

8 Creating Instances of Objects and ComponentsSpecifying a ClassID CLASSID=“clsid:892D6DA7-E0F9-11D2-B2E A42AF30”> 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. Bina Nusantara

9 Creating Instances of Objects and ComponentsSetting 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 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 Creating objects with Session-Level Scope SCOPE=“APPLICATION” > SCOPE=“SESSION” > Bina Nusantara

10 Creating Instances of Objects and ComponentsThe Difference between Server.CreateObject & Server.CreateObject creates an instance of the object immediately. can remove objects from a Session or Application The 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 Bina Nusantara

11 The Scripting.Dictionary ObjectMany 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 two-dimensional array, holding the key and the related item of data together. Bina Nusantara

12 Creating and Using Dictionary Objects‘ In VBScript Dim objMyData Set objMyData = Server.CreateObject(“Scripting.Dictionary”) // In JSCript var objMyData = Server.CreateObject(“Scripting.Dictionary”) PROGID=“Scripting.Dictionary” > The Dictionary object can also be used client-side in Internet Explorer. Bina Nusantara

13 The Dictionary Object Members SummaryThe 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. Bina Nusantara

14 Adding Items To and Removing Items From a Dictionary‘In VBScript : objMyData.Add “MyKey”, “MyItem” ‘Add value MyItem with key MyKey objMyData.Add “YourKey”, “YourItem” ‘Add value YourItem with key YourKey blnIsThere = objMyData.Exists(“MyKey”) ‘Returns True because the item exists StrItem = objMyData.Item(“YourKey”) ‘Retrieve value of YourKey StrItem = objMyData.Remove(“MyKey”) ‘Retrieve and remove Mykey objMyData.RemoveAll ‘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 Bina Nusantara

15 Changing the Value of a Key or ItemTo 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 Bina Nusantara

16 Iterating Through a Dictionary‘In VBScript : arrKeys = objMyData.Keys ‘Get all the keys into array arrItems = objMyData.Items ‘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 } Bina Nusantara

17 Iterating Through a DictionaryAlternatively 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) & “
Next Bina Nusantara

18 The Scripting.FileSystemObject ObjectThe 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 element in the section of the page, for example: Bina Nusantara

19 The Scripting.FileSystemObject ObjectWe 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”) PROGID=“Scripting.FileSystemObject” > The type library for the complete scripting Runtime library can be added to any ASP page using: Bina Nusantara

20 The Scripting.FileSystemObject Members SummaryThe FileSystemObject’s Property Property Description Drives 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”. Bina Nusantara

21 The Scripting.FileSystemObject Members SummaryThe 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. Bina Nusantara

22 The Scripting.FileSystemObject Members SummaryMethod 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. Bina Nusantara

23 The Scripting.FileSystemObject Members SummaryMethod 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. Bina Nusantara

24 The Scripting.FileSystemObject Members SummaryThe 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. Bina Nusantara

25 The Scripting.FileSystemObject Members SummaryMethod 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 (filespec) Returns just the file extension of a file specified in filespec, i.e. with 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. Bina Nusantara

26 The Scripting.FileSystemObject Members SummaryMethod 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. Bina Nusantara

27 Working with Drives Get a list of available drive letters using the DriveExists method. ‘ In VBScript Response.Write "

Using the DriveExists Method

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 & “ :
End If Next Bina Nusantara

28 The Drive Object Property Description AvailableSpaceReturns 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. Bina Nusantara

29 The Drive Object <% 'In VBScript:Set objFSO = Server.CreateObject("Scripting.FileSystemObject") Set colDrives = objFSO.Drives 'Create a Drives collection Response.Write "

Using the Drives Collection

" For Each objDrive in colDrives 'Iterate through the Drives collection Response.Write "DriveLetter : " & objDrive.DriveLetter & "
"
Response.Write "DriveType : " & objDrive.DriveType If objDrive.DriveType = 3 Then If objDrive.IsReady Then Response.Write "Remote drive with ShareName: " & objDrive.ShareName & "
"
Else Response.Write "Remote drive - IsReady property returned False
"
End If Response.Write "FileSystem: " & objDrive.FileSystem & ", " Response.Write "SerialNumber: " & objDrive.SerialNumber & "
"
Response.Write "Local drive with VolumeName: " & objDrive.VolumeName & ", " Response.Write "AvailableSpace: " & objDrive.AvailableSpace & " bytes, " Response.Write "FreeSpace: " & objDrive.FreeSpace & " bytes, " Response.Write "TotalSize: " & objDrive.TotalSize & " bytes

"
Next %> Bina Nusantara

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 Bina Nusantara

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. Bina Nusantara

32 The Folder Object Property Description PathReturns 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 Description Copy (destination, overwrite) 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. Bina Nusantara

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. Bina Nusantara

34 The Folder Object <% 'In VBScriptResponse.Write "

Using the Folders Collection

" 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 & "
"
Response.Write "Path: " & objFolder.Path & "  " Response.Write "ShortPath: " & objFolder.ShortPath & "
"
Response.Write "Created: " & objFolder.DateCreated & "  " Response.Write "LastModified: " & objFolder.DateLastModified & "

" Next %> Bina Nusantara

35 The Folder Object Bina Nusantara

36 The Folder Object Working with Special FoldersGetSpecialFolder 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) Bina Nusantara

37 The Folder Object <% 'In VBScriptResponse.Write "

Using the SpecialFolders Method

"
Set objFSO = Server.CreateObject("Scripting.FileSystemObject") Set objFolder = objFSO.GetSpecialFolder(WindowsFolder) Response.Write "GetSpecialFolder(WindowsFolder) returned:
"
Response.Write "Path: " & objFolder.Path & "
"
Response.Write "Type: " & objFolder.Type & "

" Set objFolder = objFSO.GetSpecialFolder(SystemFolder) Response.Write "GetSpecialFolder(SystemFolder) returned:
"
Set objFolder = objFSO.GetSpecialFolder(TemporaryFolder) Response.Write "GetSpecialFolder(TemporaryFolder) returned:
"
%> Bina Nusantara

38 The Folder Object Bina Nusantara

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. Bina Nusantara

40 The File Object Property Description ParentFolderReturns 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 Description Copy (destination, overwrite) 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. Bina Nusantara

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. Bina Nusantara

42 The File Object <% 'In VBScriptResponse.Write "

Using the Files Collection

"
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 & "
"
Response.Write "Type: " & objFile.Type & "
"
Response.Write "Path: " & objFile.Path & "  " Response.Write "ShortPath: " & objFile.ShortPath & "
"
Response.Write "Created: " & objFile.DateCreated & "  " Response.Write "LastModified: " & objFile.DateLastModified & "

" %> Bina Nusantara

43 The File Object Bina Nusantara

44 The Scripting.TextStream ObjectMethods 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 OpenTextFile (No) OpenAsTextStream Bina Nusantara

45 The Scripting.TextStream ObjectCreating 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. Bina Nusantara

46 The Scripting.TextStream ObjectOpening Existing Text Files To open file for writing, and create a new file if the one specified doesn’t exists ‘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’); ‘In VBScript Set objTStream = objFSO.OpenTextFile(“C:\TextFiles\MyFile.txt”, ForWriting, True) ‘In JScript var objTStream = objFSO.OpenTextFile(‘C:\TextFiles\MyFile.txt’, ForWriting, true); Bina Nusantara

47 The Scripting.TextStream ObjectOpening 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); Bina Nusantara

48 The Scripting.TextStream ObjectOpening a File Object as a TextStream Object To start with a new empty file To read from the file ‘In VBScript Set objTStream = objFileObject.OpenAsTextStream(ForAppending, False) ‘In JScript var objTStream = objFileObject.OpenTextFile(ForAppending, false); ‘In VBScript Set objTStream = objFileObject.OpenAsTextStream(ForWriting) ‘In JScript var objTStream = objFileObject.OpenTextFile(ForWriting); ‘In VBScript Set objTStream = objFileObject.OpenAsTextStream(ForReading) ‘In JScript var objTStream = objFileObject.OpenTextFile(ForReading); Bina Nusantara

49 The Scripting.TextStream ObjectProperty 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. Bina Nusantara

50 The Scripting.TextStream ObjectMethod 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. Bina Nusantara

51 The Scripting.TextStream ObjectWriting 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(); Bina Nusantara

52 The Scripting.TextStream ObjectReading 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 & “
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 &
’);
} objTStream.Close(); Bina Nusantara