Cara membaca file teks di server menggunakan VBScript di ASP
Salah satu tugas terpenting dalam bahasa pemrograman apa pun adalah kemampuan membaca dan menulis file. Langkah-langkah yang terlibat dalam ASP tidak berbeda dengan banyak bahasa lainnya:
File I/O di ASP dapat dilakukan dengan menggunakan komponen FileSystemObject
. Saat membuka file teks, Anda cukup membukanya sebagai aliran teks, dan aliran teks inilah yang Anda gunakan untuk mengakses konten file.
FileSystemObject memungkinkan Anda melakukan semua operasi penanganan file dan folder. Itu bisa mengembalikan file yang kemudian bisa dibuka sebagai aliran teks, atau bisa mengembalikan objek aliran teks secara langsung.
Berikut ini saya menyajikan dua metode berbeda. Metode pertama mendapatkan objek file dan menggunakannya untuk membuka aliran teks, dan metode kedua membuka aliran teks langsung dari FileSystemObject
.
"
' Open the file
Dim TextStream
Set TextStream = file.OpenAsTextStream(ForReading, TristateUseDefault)
' Read the file line by line
Do While Not TextStream.AtEndOfStream
Dim Line
Line = TextStream.readline
' Do something with "Line"
Line = Line & vbCRLF
Response.write Line
Loop
Response.Write "
<% Option Explicit
Const Filename = " /readme.txt " ' file to read
Const ForReading = 1 , ForWriting = 2 , ForAppending = 3
Const TristateUseDefault = - 2 , TristateTrue = - 1 , TristateFalse = 0
' Create a filesystem object
Dim FSO
set FSO = server . createObject ( " Scripting.FileSystemObject " )
' Map the logical path to the physical system path
Dim Filepath
Filepath = Server . MapPath (Filename)
if FSO.FileExists(Filepath) Then
' Get a handle to the file
Dim file
set file = FSO.GetFile(Filepath)
' Get some info about the file
Dim FileSize
FileSize = file.Size
Response . Write " File: "
& Filename & " (size " & FileSize & _
" bytes)
"
Response . Write " "
' Open the file
Dim TextStream
Set TextStream = file.OpenAsTextStream(ForReading, TristateUseDefault)
' Read the file line by line
Do While Not TextStream.AtEndOfStream
Dim Line
Line = TextStream.readline
' Do something with "Line"
Line = Line & vbCRLF
Response . write Line
Loop
Response . Write "
<% Option Explicit
Const Filename = " /readme.txt " ' file to read
Const ForReading = 1 , ForWriting = 2 , ForAppending = 3
Const TristateUseDefault = - 2 , TristateTrue = - 1 , TristateFalse = 0
' Create a filesystem object
Dim FSO
set FSO = server . createObject ( " Scripting.FileSystemObject " )
' Map the logical path to the physical system path
Dim Filepath
Filepath = Server . MapPath (Filename)
if FSO.FileExists(Filepath) Then
Set TextStream = FSO.OpenTextFile(Filepath, ForReading, False , TristateUseDefault)
' Read file in one hit
Dim Contents
Contents = TextStream.ReadAll
Response . write " "
& Contents & "