Sie sind auf Seite 1von 26

§¹i häc Th¸i Nguyªn – Tr−êng §HSP – Khoa To¸n -Tin

LËp tr×nh trªn Windows víi Visual Basic

Ch−¬ng 5
Xö lý tÖp tin

Trong ch−¬ng nµy chóng ta sÏ xem xÐt mét sè thao t¸c c¬ b¶n víi c¸c
tÖp tin trong VB, nh− c¸c thao t¸c: ghi néi dung tÖp lªn ®Üa, ®äc tÖp tõ ®Üa,
xem danh s¸ch tÖp ...

5.1. M« h×nh FSO (File System Object mode)


M« h×nh FSO chøa trong th− viÖn Scrun.dll, hç trî t¹o vµ thao t¸c víi
c¸c tÖp tin v¨n b¶n th«ng th−êng th«ng qua ®èi t−îng TextStream. M« h×nh
nµy chøa c¸c ®èi t−îng sau:
§èi t−îng Gi¶i thÝch
Drive Cho phÐp thao t¸c víi æ ®Üa: Dung l−îng, tªn ...
Folder Thao t¸c víi th− môc: T¹o, xo¸, di chuyÓn, tªn th− môc, ®−êng
dÉn...
Files Thao t¸c víi tÖp tin: T¹o, xo¸, di chuyÓn, tªn tÖp, ®−êng dÉn ...
FileSystemObject C¸c thuéc tÝnh vµ c¸c ph−¬ng thøc cho phÐp t¹o, xo¸, thu thËp
th«ng tin vÒ æ ®Üa th− môc vµ tÖp tin.
TextStream Cho phÐp xö lý (®äc, ghi ...) c¸c tÖp tin v¨n b¶n.

NÕu ch−a cã s½n tham chiÕu ®Õn ®èi t−îng FSO, tõ menu Project chän
Refrence, hép tho¹i Refrence xuÊt hiÖn h·y ®¸nh dÊu vµo môc Microsort
Scripting Runtime, råi chän OK.
5.1.1. T¹o ®èi t−îng FileSystemObject
Cã thÓ t¹o b»ng hai c¸ch:
• Khai b¸o:
Dim fso as New FileSystemObject
• Dïng ph−¬ng thøc CreateObject
Set fso = CreateObject(“Scripting.FileSystemObject”)

46
§¹i häc Th¸i Nguyªn – Tr−êng §HSP – Khoa To¸n -Tin
LËp tr×nh trªn Windows víi Visual Basic

Scripting lµ tªn th− viÖn, FileSystemObject lµ tªn ®èi t−îng mµ ta muèn


t¹o mét instance.
5.1.2. Sö dông ph−¬ng thøc cña FileSystemObject
NÕu muèn t¹o ®èi t−îng míi, cã thÓ dïng ph−¬ng thøc Create Folder
hay CreateTextFile.
NÕu muèn xo¸ ®èi t−îng, cã thÓ dïng ph−¬ng thøc DeleteFile hay
DeleteFolder.
Di chuyÓn hay sao chÐp tÖp tin/th− môc: FileSystemObject.CopyFile,
FileSystemObject.MoveFolder ...
5.1.3. Truy nhËp æ ®Üa, tÖp tin, th− môc hiÖn hµnh
Dïng GetDrive, GetFolder, GetFile.
VÝ dô:
Dim fso As New FileSystemObject, teptin As File
Set teptin = fso.GetFile(“C:\TEXT.TXT”)

Private Sub Create_Folder()


Dim fso As New FileSystemObject, fldr As Folder
Set fldr = fso.CreateFolder("C:\MYFOLDER")
MsgBox "You created Folder : " & fldr.Name
End Sub

5.1.4. Truy cËp thuéc tÝnh cña ®èi t−îng


Set fldr = fso.GetFolder(“C:\”)
Print “Folder name is: “; fldr.Name

5.1.5. C¸c thuéc tÝnh vÒ th«ng tin vÒ æ ®Üa


Thuéc tÝnh C¸c th«ng tin
TotalSize Tæng dung l−îng ®Üa (byte)
AvailableSpace, Dung l−îng trèng cña ®Üa (byte)
FreeSpace
DriveLetter Ký tù cña æ ®Üa
DriveType Lo¹i æ ®Üa

47
§¹i häc Th¸i Nguyªn – Tr−êng §HSP – Khoa To¸n -Tin
LËp tr×nh trªn Windows víi Visual Basic

SerialNumber Sè serial
FileSystem FAT, FAT32, NTFS ...
IsReady æ cã sö dông ®−îc kh«ng.
ShareName, Tªn chia sÎ trong m¹ng
VolumeName
Path, Th− môc gèc
RootFolder

VÝ dô:
Dim fso As New FileSystemObject, drv As Drive
Set drv = fso.GetDrive(fso.GetDriveName)
MsgBox “Total Size = “ & str(drv.TotalSize)

5.1.6. C¸c thao t¸c víi th− môc


T¸c vô Ph−¬ng thøc
T¹o th− môc FileSystemObject.CreateFolder
Xo¸ th− môc Folder.Delete
FileSystemObject.DeleteFolder
ChuyÓn th− môc Folder.Move
FileSystemObject.MoveFolder
Sao chÐp th− môc Folder.Copy
FileSystemObject.CopyFolder
LÊy tªn th− môc Folder.Name
KiÓm tra xem cã tån FileSystemObject.FolderExits
t¹i th− môc kh«ng
Tr¶ vÒ ®èi t−îng FileSystemObject.GetFolder
Folder
LÊy tªn th− môc cha FileSystemObject.GetParentFolderName
LÊy tªn cña th− môc FileSystemObject.GetSpecialFolder
hÖ thèng

48
§¹i häc Th¸i Nguyªn – Tr−êng §HSP – Khoa To¸n -Tin
LËp tr×nh trªn Windows víi Visual Basic

VÝ dô:
Dim fso As New FileSystemObject, fld As Folder
Set fld = fso.GetFolder(“C:”)
Print “Drive is: “ & fld.Drive
Print “Name folder is: “&fld.Name

5.1.7. C¸c thao t¸c víi tÖp tin


5.1.7.1. T¹o tÖp vµ thªm d÷ liÖu
C¸ch 1: Dïng ph−¬ng thøc CreateTextFile ®Ó t¹o tÖp tin v¨n b¶n rçng,
vÝ dô:
Dim fso As New FileSystemObject, FileName As File
Set FileName=fso.CreateTextFile(“C:\test.txt”, True)

C¸ch 2: Dïng OpenTextFile cña ®èi t−îng FileSystemObject víi cê


ForWriting, vÝ dô:
Dim fso As New FileSystemObject
Dim tt As New TextStream
Set tt = fso.OpenTextFile(“C:\test.txt”, ForWriting)

C¸ch 3: Dïng ph−¬ng thøc OpenAsTextStream víi cê ForWriting


Dim fso As New FileSystemObject, FileName As File,
ts as TextStream
Set fso = CreateObject(“Scripting.FileSystemObject”)
Set FileName=fso.CreateTextFile(“C:\test.txt”, True)
Set ts = FileName.OpenAsTextStream(ForWriting)

Thªm d÷ liÖu vµo tÖp: Sau khi ®· t¹o tÖp, ®Ó thªm d÷ liÖu vµo tÖp ta lµm
theo c¸c b−íc sau:
• Më tÖp cÇn thªm d÷ liÖu: OpenTextFile
• Ghi d÷ liÖu: Write hoÆc WriteLine hoÆc WriteBlankLines
• §ãng tÖp: Close

49
§¹i häc Th¸i Nguyªn – Tr−êng §HSP – Khoa To¸n -Tin
LËp tr×nh trªn Windows víi Visual Basic

VÝ dô:

Private Sub Create_File_Text()


Dim fso, txtFile
Set fso = CreateObject(“Scripting.FileSystemObject”)
Set txtFile = fso.CreateTextFile(“c:\test.txt”,True)
txtFile.Write(“This is a test. “)
txtFile.WriteLine(“Testing 1, 2, 3 ...”)
txtFile.WriteBlankLines(2)
txtFile.Close
End sub

5.1.7.2. §äc tÖp víi FSO


T¸c vô Ph−¬ng thøc
§äc mét sè ký tù tõ tÖp Read
§äc mét dßng nh−ng kh«ng tÝnh ReadLine
ký tù xuèng dßng
§äc néi cña c¶ tÖp ReadAll

5.1.7.3. Di chuyÓn, sao chÐp, xo¸ tÖp tin


T¸c vô Ph−¬ng thøc
ChuyÓn tÖp File.Move
FileSystemObject.MoveFile
Sao chÐp tÖp File.Copy
FileSystemObject.CopyFile
Xo¸ tÖp File.Delete
FileSystemObject.DeleteFile
LÊy tªn tÖp File.Name

50
§¹i häc Th¸i Nguyªn – Tr−êng §HSP – Khoa To¸n -Tin
LËp tr×nh trªn Windows víi Visual Basic

VÝ dô: C¸c thao t¸c víi tÖp theo m« h×nh FSO


ThiÕt kÕt giao diÖn

MÉ tr×nh ®Çy ®ñ:


VERSION 5.00
Begin VB.Form frmFSO
BackColor = &H00C0C0C0&
Caption = "M« h×nh FSO"
ClientHeight = 3120
ClientLeft = 60
ClientTop = 345
ClientWidth = 5880
BeginProperty Font
Name = "MS Sans Serif"
Size = 8.25
Charset = 0
Weight = 700
Underline = 0 'False
Italic = 0 'False
Strikethrough = 0 'False
EndProperty
LinkTopic = "Form1"
ScaleHeight = 3120
ScaleWidth = 5880
StartUpPosition = 2 'CenterScreen
Begin VB.CommandButton cmdCopy
Caption = "&C&opy File"
Height = 495
Left = 4200
TabIndex = 7
Top = 1920

51
§¹i häc Th¸i Nguyªn – Tr−êng §HSP – Khoa To¸n -Tin
LËp tr×nh trªn Windows víi Visual Basic

Width = 1335
End
Begin VB.CommandButton cmdExit
Caption = "&Exit"
Height = 495
Left = 4200
TabIndex = 3
Top = 2520
Width = 1335
End
Begin VB.CommandButton cmDoc_File
Caption = "&Read File"
Height = 495
Left = 4200
TabIndex = 2
Top = 1320
Width = 1335
End
Begin VB.CommandButton cmdNhap_DL
Caption = "&Input Data"
Height = 495
Left = 4200
TabIndex = 1
Top = 720
Width = 1335
End
Begin VB.CommandButton cmdTao_File
Caption = "&Create File"
Height = 495
Left = 4200
TabIndex = 0
Top = 120
Width = 1335
End
Begin VB.Label Label3
AutoSize = -1 'True
Caption = "FSO"
BeginProperty Font
Name = "Arial"
Size = 36
Charset = 0
Weight = 700
Underline = 0 'False
Italic = 0 'False
Strikethrough = 0 'False
EndProperty
ForeColor = &H00FF00FF&

52
§¹i häc Th¸i Nguyªn – Tr−êng §HSP – Khoa To¸n -Tin
LËp tr×nh trªn Windows víi Visual Basic

Height = 840
Left = 1440
TabIndex = 6
Top = 1800
Width = 1470
End
Begin VB.Label Label2
AutoSize = -1 'True
Caption = "FileSystemObject"
BeginProperty Font
Name = ".VnAristote"
Size = 27.75
Charset = 0
Weight = 500
Underline = 0 'False
Italic = -1 'True
Strikethrough = 0 'False
EndProperty
ForeColor = &H000000FF&
Height = 555
Left = 240
TabIndex = 5
Top = 1080
Width = 3735
End
Begin VB.Label Label1
AutoSize = -1 'True
BackColor = &H00C0C0C0&
Caption = "M« h×nh"
BeginProperty Font
Name = ".VnAristote"
Size = 27.75
Charset = 0
Weight = 500
Underline = 0 'False
Italic = -1 'True
Strikethrough = 0 'False
EndProperty
ForeColor = &H00FF0000&
Height = 555
Left = 1200
TabIndex = 4
Top = 360
Width = 1815
End
End
Attribute VB_Name = "frmFSO"

53
§¹i häc Th¸i Nguyªn – Tr−êng §HSP – Khoa To¸n -Tin
LËp tr×nh trªn Windows víi Visual Basic

Attribute VB_GlobalNameSpace = False


Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Option Explicit

Private Sub cmdExit_Click()


End
End Sub

Private Sub cmdTao_File_Click()


Dim fso, txtFile
Set fso=CreateObject("Scripting.FileSystemObject")
Set txtFile=fso.CreateTextFile("c:\test.txt",True)
txtFile.Close
MsgBox "File C:\test.txt created."
End Sub

Private Sub cmdNhap_DL_Click()


Dim fso, txtFile, fil
Set fso=CreateObject("Scripting.FileSystemObject")
Set txtFile=fso.OpenTextFile("c:\test.txt",
ForWriting)
txtFile.Write ("This is a test. ")
txtFile.WriteLine ("Testing 1, 2, 3 ...")
txtFile.WriteBlankLines (2)
txtFile.WriteLine ("This is the last Line. ")
txtFile.Close
MsgBox "Inputed Data into File C:\test.txt."
End Sub

Private Sub cmDoc_File_Click()


Dim fso As New FileSystemObject, txtFile As File
Dim ts As TextStream, s As String
Set txtFile = fso.GetFile("c:\test.txt")
Set ts = txtFile.OpenAsTextStream(ForReading)
s = ts.ReadAll
MsgBox s
End Sub

Private Sub cmdCopy_Click()


Dim fso As New FileSystemObject, txtFile As File
Set txtFile = fso.GetFile("c:\test.txt")
txtFile.Copy "c:\bp\test.txt", True
MsgBox "Copeid this file to c:\bp"
End Sub

54
§¹i häc Th¸i Nguyªn – Tr−êng §HSP – Khoa To¸n -Tin
LËp tr×nh trªn Windows víi Visual Basic

5.2. Xö lý tÖp víi c¸c dßng lÖnh vµ c¸c hµm I/O


MÆc dï cã FSO, c¸c lÖnh thao t¸c truyÒn thèng víi tÖp tin vÉn ®−îc hç
trî ®Çy ®ñ trong VB.
5.2.1. C¸c kiÓu truy cËp tÖp tin
TuÇn tù: §äc vµ ghi c¸c tÖp v¨n b¶n theo c¸c khèi liªn tôc.
NgÉu nhiªn: §äc vµ ghi c¸c tÖp tin v¨n b¶n hoÆc nhÞ ph©n cã cÊu tróc
theo c¸c mÈu tin cã ®é réng x¸c ®Þnh.
NhÞ ph©n: §äc vµ ghi c¸c tÖp tin cã cÊu tróc kh«ng cè ®Þnh.
C¸c hµm truy cËp tÖp tin:
Tªn hµm T¸c dông
Dir ChØ ®Þnh th− môc
EOF KiÓm tra ®¸y tÖp
FileCopy Sao chÐp tÖp
FileDateTime Tr¶ vÒ thêi gian tÖp ®−îc t¹o ra
FileLen Tr¶ vÒ ®é lín cña tÖp (byte)
FreeFile Tr¶ vÒ sè hiÖu tÖp tin
GetAttr Tr¶ vÒ sè nguyªn chØ thuéc tÝnh cña tÖp
LOF Tr¶ vÒ ®é lín cña tÖp
Seek Trá tíi b¶n ghi nµo
SetAttr X¸c lËp c¸c thuéc tÝnh cho tÖp

Tªn hµm/lÖnh Thao t¸c víi lo¹i tÖp

TuÇn tù NgÉu nhiªn NhÞ ph©n


Close X X X
Get X X
Input # X
Line Input # X
Open X X X
Print # X

55
§¹i häc Th¸i Nguyªn – Tr−êng §HSP – Khoa To¸n -Tin
LËp tr×nh trªn Windows víi Visual Basic

Put X X
Type ... End Type X
Write X

5.2.2. TÖp tin tuÇn tù


5.2.2.1. Më tÖp tuÇn tù
Open FileName For | Input | Output | Append | As Filenumber |
[Len = bufersize]
Chó ý:
• Khi më tÖp tuÇn tù víi Input tÖp tin ph¶i cã s½n, nÕu kh«ng
VB sÏ b¸o lçi.
• Khi më tÖp tuÇn tù víi Output hoÆc Append nÕu tÖp tin ch−a
cã s½n th× VB sÏ t¹o ra më nã.
• Tham sè Len chØ sè ký tù trong vïng ®Öm khi sao chÐp gi÷a
tÖp vµ ch−¬ng tr×nh.
5.2.2.1. Ghi d÷ liÖu vµo tÖp tuÇn tù
Më tÖp víi Output hoÆc Append.
Ghi vµo b»ng lÖnh: Print #FileNum, <d÷ liÖu>
hoÆc lÖnh : Write #FileNum, <d÷ liÖu>
5.2.2.1. §äc d÷ liÖu tõ tÖp tuÇn tù
Më tÖp víi Input.
Dïng c¸c lÖnh: Line Input #, Input(), Input #, Get # ... ®Ó sao chÐp néi
dung tÖp vµo biÕn.
VÝ dô:
ThiÕt kÕ giao diÖn:

56
§¹i häc Th¸i Nguyªn – Tr−êng §HSP – Khoa To¸n -Tin
LËp tr×nh trªn Windows víi Visual Basic

M· tr×nh ®Çy ®ñ:


VERSION 5.00
Begin VB.Form frmFile
AutoRedraw = -1 'True
BackColor = &H00E0E0E0&
Caption = "Xö lý TÖp tin"
ClientHeight = 2625
ClientLeft = 60
ClientTop = 345
ClientWidth = 5790
BeginProperty Font
Name = "MS Sans Serif"
Size = 8.25
Charset = 0
Weight = 700
Underline = 0 'False
Italic = 0 'False
Strikethrough = 0 'False
EndProperty
LinkTopic = "Form1"
ScaleHeight = 2625
ScaleWidth = 5790
StartUpPosition = 2 'CenterScreen
Begin VB.CommandButton cmdThoat
Caption = "&Tho¸t ra"
Height = 495
Left = 4200
TabIndex = 2
Top = 1800
Width = 1215
End
Begin VB.CommandButton cmDoctep
Caption = "&§äc tÖp"
Height = 495
Left = 4200
TabIndex = 1
Top = 1080
Width = 1215
End
Begin VB.CommandButton cmdTaotep
Caption = "&T¹o tªp"
Height = 495
Left = 4200
TabIndex = 0
Top = 360
Width = 1215

57
§¹i häc Th¸i Nguyªn – Tr−êng §HSP – Khoa To¸n -Tin
LËp tr×nh trªn Windows víi Visual Basic

End
End
Attribute VB_Name = "frmFile"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Option Explicit
Dim FileNum As Integer

Private Sub cmdTaotep_Click()


FileNum = FreeFile
Open "Vidu.txt" For Output As FileNum
Dim i As Integer
For i = 1 To 10
Print #FileNum, "Day la dong so " & Str(i)
Next i
Close #FileNum
MsgBox "§· t¹o xong tÖp", 48, "Xö lý tÖp tin"
End Sub

Private Sub cmDoctep_Click()


FileNum = FreeFile
Open "Vidu.txt" For Input As FileNum
Dim i As Integer, s As String
frmFile.Cls
Do Until EOF(FileNum)
Line Input #FileNum, s
Print s
Loop
Close #FileNum
End Sub

Private Sub cmdThoat_Click()


End
End Sub

5.2.3. TÖp tin ngÉu nhiªn


5.2.3.1. Kh¸i niÖm
M« h×nh FSO kh«ng hç trî cho tÖp tin ngÉu nhiªn. C¸c byte trong tÖp
tin ngÉu nhiªn cã d¹ng c¸c mÈu tin ®ång nhÊt, mçi mÈu tin (record) chøa
mét hoÆc nhiÒu tr−êng (field). Mçi tr−êng cã kiÓu vµ kÝch th−íc x¸c ®Þnh. VÝ
dô:

58
§¹i häc Th¸i Nguyªn – Tr−êng §HSP – Khoa To¸n -Tin
LËp tr×nh trªn Windows víi Visual Basic

Type HOSO
Ho_ten As String*25
Tuoi As Integer
Que_quan As String*30
He_so_luong As Double
End Type
Dim Nguoi As HOSO

5.2.3.2. Më tÖp tin ngÉu nhiªn

Open FileName [For Random] As Filenumber Len = Reclength


Trong ®ã
For Random lµ mÆc ®Þnh
Len = Reclength chØ ra kÝch th−íc (byte) cña mét mÈu tin.

5.2.3.2.Ghi biÕn record vµo tÖp ngÉu nhiªn


§Ó thªm mÈu tin vµo cuèi tÖp, h·y dïng lÖnh Put. Gi¸ trÞ cña Position
b»ng sè mÈu tin trong tÖp + 1.
LastRecord = LastRecord + 1
Put #FileNum, LastRecord, Nguoi
Thay thÕ mÈu tin:
Put #FileNum, Position, Nguoi

VÝ dô:
Giao diÖn

59
§¹i häc Th¸i Nguyªn – Tr−êng §HSP – Khoa To¸n -Tin
LËp tr×nh trªn Windows víi Visual Basic

M· tr×nh ®Çy ®ñ:


Module
Type PersonInfo
Name As String * 25
Phone As String * 12
Comments As String * 50
End Type
=================================================

VERSION 5.00
Begin VB.Form FrmPhone
ClientHeight = 2790
ClientLeft = 60
ClientTop = 345
ClientWidth = 6420
LinkTopic = "Form1"
MaxButton = 0 'False
ScaleHeight = 2790
ScaleWidth = 6420
StartUpPosition = 2 'CenterScreen
Begin VB.CommandButton cmdExit
Caption = "Exit"
BeginProperty Font
Name = "MS Sans Serif"
Size = 8.25
Charset = 0
Weight = 700
Underline = 0 'False
Italic = 0 'False
Strikethrough = 0 'False
EndProperty
Height = 375
Left = 5040
TabIndex = 6
ToolTipText = "Tho¸t ra"
Top = 2280
Width = 1215
End
Begin VB.CommandButton cmdPrevious
Caption = "Previous"
BeginProperty Font
Name = "MS Sans Serif"
Size = 8.25
Charset = 0
Weight = 700
Underline = 0 'False

60
§¹i häc Th¸i Nguyªn – Tr−êng §HSP – Khoa To¸n -Tin
LËp tr×nh trªn Windows víi Visual Basic

Italic = 0 'False
Strikethrough = 0 'False
EndProperty
Height = 375
Left = 5040
TabIndex = 5
ToolTipText = "Trë l¹i b¶n ghi tr−íc"
Top = 1680
Width = 1215
End
Begin VB.CommandButton cmdNext
Caption = "Next"
BeginProperty Font
Name = "MS Sans Serif"
Size = 8.25
Charset = 0
Weight = 700
Underline = 0 'False
Italic = 0 'False
Strikethrough = 0 'False
EndProperty
Height = 375
Left = 5040
TabIndex = 4
ToolTipText = "Sang b¶n ghi tiÕp"
Top = 1080
Width = 1215
End
Begin VB.CommandButton cmdNew
Caption = "New"
BeginProperty Font
Name = "MS Sans Serif"
Size = 8.25
Charset = 0
Weight = 700
Underline = 0 'False
Italic = 0 'False
Strikethrough = 0 'False
EndProperty
Height = 375
Left = 5040
TabIndex = 3
ToolTipText = "Thªm b¶n ghi míi"
Top = 480
Width = 1215
End

61
§¹i häc Th¸i Nguyªn – Tr−êng §HSP – Khoa To¸n -Tin
LËp tr×nh trªn Windows víi Visual Basic

Begin VB.TextBox txtComment


BackColor = &H00FFFFC0&
BeginProperty Font
Name = "MS Sans Serif"
Size = 8.25
Charset = 0
Weight = 700
Underline = 0 'False
Italic = 0 'False
Strikethrough = 0 'False
EndProperty
Height = 1080
Left = 120
MaxLength = 100
MultiLine = -1 'True
ScrollBars = 2 'Vertical
TabIndex = 2
Top = 1560
Width = 4455
End
Begin VB.TextBox txtPhone
BackColor = &H00FFFFC0&
BeginProperty Font
Name = "MS Sans Serif"
Size = 8.25
Charset = 0
Weight = 700
Underline = 0 'False
Italic = 0 'False
Strikethrough = 0 'False
EndProperty
Height = 285
Left = 840
MaxLength = 40
TabIndex = 1
Top = 720
Width = 3735
End
Begin VB.TextBox txtName
BackColor = &H00FFFFC0&
BeginProperty Font
Name = "MS Sans Serif"
Size = 8.25
Charset = 0
Weight = 700
Underline = 0 'False
Italic = 0 'False

62
§¹i häc Th¸i Nguyªn – Tr−êng §HSP – Khoa To¸n -Tin
LËp tr×nh trªn Windows víi Visual Basic

Strikethrough = 0 'False
EndProperty
Height = 285
Left = 840
MaxLength = 40
TabIndex = 0
Top = 240
Width = 3735
End
Begin VB.Label lblName
Caption = "Name:"
BeginProperty Font
Name = "MS Sans Serif"
Size = 8.25
Charset = 0
Weight = 700
Underline = 0 'False
Italic = 0 'False
Strikethrough = 0 'False
EndProperty
Height = 255
Left = 120
TabIndex = 9
Top = 240
Width = 615
End
Begin VB.Label lblPhone
Caption = "Phone:"
BeginProperty Font
Name = "MS Sans Serif"
Size = 8.25
Charset = 0
Weight = 700
Underline = 0 'False
Italic = 0 'False
Strikethrough = 0 'False
EndProperty
Height = 255
Left = 120
TabIndex = 8
Top = 720
Width = 615
End
Begin VB.Label lblComment
Caption = "Comments:"
BeginProperty Font
Name = "MS Sans Serif"

63
§¹i häc Th¸i Nguyªn – Tr−êng §HSP – Khoa To¸n -Tin
LËp tr×nh trªn Windows víi Visual Basic

Size = 8.25
Charset = 0
Weight = 700
Underline = 0 'False
Italic = 0 'False
Strikethrough = 0 'False
EndProperty
Height = 255
Left = 120
TabIndex = 7
Top = 1200
Width = 1215
End
End
Attribute VB_Name = "FrmPhone"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Option Explicit

Dim Person As PersonInfo


Dim FileNum As Integer
Dim RecordLen As Long
Dim CurrentRecord As Long
Dim LastRecord As Long

Private Sub cmdExit_Click()


SaveCurrentRecord
Close FileNum
End
End Sub

Public Sub SaveCurrentRecord()


Person.Name = txtName.Text
Person.Phone = txtPhone.Text
Person.Comments = txtComment.Text

Put #FileNum, CurrentRecord, Person


End Sub

Public Sub ShowCurrentRecord()


Get #FileNum, CurrentRecord, Person
txtName.Text = Trim(Person.Name)
txtPhone.Text = Trim(Person.Phone)
txtComment.Text = Trim(Person.Comments)
FrmPhone.Caption = "DataBase File, Record " +

64
§¹i häc Th¸i Nguyªn – Tr−êng §HSP – Khoa To¸n -Tin
LËp tr×nh trªn Windows víi Visual Basic

Str(CurrentRecord) + "/" + Str(LastRecord)


End Sub

Private Sub cmdNew_Click()


SaveCurrentRecord
LastRecord = LastRecord + 1
Person.Name = ""
Person.Phone = 0
Person.Comments = ""
Put #FileNum, LastRecord, Person
CurrentRecord = LastRecord
ShowCurrentRecord
txtName.SetFocus
End Sub

Private Sub cmdNext_Click()


If CurrentRecord = LastRecord Then
Beep
MsgBox "§· kÕt thóc tÖp !", 48
Else
SaveCurrentRecord
CurrentRecord = CurrentRecord + 1
ShowCurrentRecord
End If
txtName.SetFocus
End Sub

Private Sub cmdPrevious_Click()


If CurrentRecord = 1 Then
Beep
MsgBox "§· ë ®Çu tÖp !", 48
Else
SaveCurrentRecord
CurrentRecord = CurrentRecord - 1
ShowCurrentRecord
End If
txtName.SetFocus
End Sub

Private Sub Form_Load()


RecordLen = Len(Person)
FileNum = FreeFile
Open "PHONE.DAT" For Random As FileNum Len =
RecordLen
CurrentRecord = 1
LastRecord = FileLen("PHONE.DAT") / RecordLen

65
§¹i häc Th¸i Nguyªn – Tr−êng §HSP – Khoa To¸n -Tin
LËp tr×nh trªn Windows víi Visual Basic

If LastRecord = 0 Then
LastRecord = 1
End If
ShowCurrentRecord
End Sub

5.2.4. TÖp tin truy cËp nhÞ ph©n


5.2.4.1. Kh¸i niÖm
M« h×nh FSO kh«ng hç trî cho tÖp tin truy cËp nhÞ ph©n. Nªn dïng tÖp
tin nhÞ ph©n khi yªu cÇu kÝch th−íc tÖp tin nhá. Khi thao t¸c nªn dïng biÕn
kiÓu byte thay v× String, v× d÷ liÖu nhÞ ph©n (binary) kh«ng thÓ chøa ®óng
vµo biÕn String.
VÝ dô:
Type HOSO
ID As Integer
Ho_ten As String*25
Tuoi As Integer
He_so_luong As Double
End Type
Dim Nhansu As HOSO

5.2.4.2. Më tÖp nhÞ ph©n

Open FileName For Benary As Filenumber

Chó ý: Kh«ng thÓ truy cËp ngÉu nhiªn víi tÖp nhÞ ph©n, mµ ph¶i truy
nhËp tuÇn tù theo chiÒu dµi cña mçi mÈu tin.

5.3. C¸c ®iÒu khiÓn trªn hÖ thèng tÖp tin


C¸c ®iÒu khiÓn nµy bao gåm:
• Hép danh s¸ch ®Üa (Drive list box).
• Hép danh s¸ch th− môc (Directory list box).
• Hép danh s¸ch tÖp tin (File list box).

66
§¹i häc Th¸i Nguyªn – Tr−êng §HSP – Khoa To¸n -Tin
LËp tr×nh trªn Windows víi Visual Basic

Chóng ta cã thÓ kÕt hîp c¸c ®iÒu khiÓn nµy ®Ó t¹o ra nh÷ng hép tho¹i
®iÒu khiÓn tÖp tin thuËn tiÖn cho ng−êi sö dông.
VÝ dô:

5.3.1. Hép danh s¸ch ®Üa (Drive list box)


Lµ hép danh s¸ch kiÓu drop-down c¸c æ ®Üa. MÆc ®Þnh lµ æ ®Üa hiÖn
hµnh ®−îc hiÓn thÞ.
Cã thÓ quy ®Þnh æ ®Üa ®−îc chän bëi m· lÖnh:
Drive1.Drive = “C:\”
5.3.2. Hép danh th− môc (Directory list box)
HiÓn thÞ c¸c th− môc cña ®Üa hiÖn hµnh.
§Þnh th− môc hiÖn hµnh theo æ ®Üa hiÖn hµnh:
Dir1.Path = Drive1.Drive
5.3.3. Hép danh tÖp tin (File list box)
HiÖn c¸c tÖp tin cña th− môc chØ ra bëi thuéc tÝnh path. Còng cã thÓ
hiÓn thÞ c¸c tÖp trong th− môc hiÖn hµnh bëi lÖnh:
File1.Path = Dir1.Path
§Ó hiÓn thÞ nhãm tÖp, th«ng qua läc theo thuéc tÝnh pattern, ch¼ng h¹n:
File1.Pattern = “*.txt; *.doc”

67
§¹i häc Th¸i Nguyªn – Tr−êng §HSP – Khoa To¸n -Tin
LËp tr×nh trªn Windows víi Visual Basic

5.3.4. KÕt hîp 3 ®iÒu khiÓn trªn víi nhau


KÕt hîp c¸c ®iÒu khiÓn hÖ thèng tÖp tin víi nhau, ta cã thÓ ®ång bé c¸c
th«ng tin hiÓn thÞ cña chóng. VÝ dô ta cã mét hép ®iÒu khiÓn æ ®Üa lµ Drive1,
hép ®iÒu khiÓn th− môc lµ Dir1 vµ hép tÖp tin lµ File1.
Tr×nh tù c¸c sù kiÖn cã thÓ xÈy ra nh− sau:
1. Ng−êi dïng chän æ ®Üa trong Drive1.
2. Sù kiÖn Drive1_Change ph¸t sinh vµ hiÓn thÞ trong Drive1 ®−îc cËp
nhËt ®Ó ph¶n ¸nh æ ®Üa míi vøa chän.
3. Thñ tôc xö lý sù kiÖn Drive1_Change g¸n gi¸ trÞ míi võa chän
(Drive1.Drive) cho thuéc thÝnh Path cña Dir1.
Private Sub Drive1_Change()
Dir1.Path = Drive1.Drive
End Sub
4. ViÖc g¸n gi¸ trÞ cho thuéc tÝnh Path lµm ph¸t sinh sù kiÖn
Dir1_Change vµ cËp nhËt hiÓn thÞ trong Dir1 ®Ó ph¶n ¸nh th− môc
hiÖn hµnh cña æ ®Üa míi.
5. Thñ tôc g¸n sù kiÖn Dir1_Change g¸n ®−êng dÉn míi (Dir1.Path)
cho File1.Path:
Private Sub Dir1_Change()
File1.Path = Dir1.Path
End Sub
6. G¸n gi¸ trÞ cho File1.Path lµm hép danh s¸ch tÖp tin hiÓn thÞ c¸c tÖp
tin cña ®−êng dÉn trong Dir1.

Sau ®©y lµ vÝ dô chän mét tÖp tin cho biÕt dung l−¬ng cña nã, theo thiÕt
kÕ m« t¶ ë trªn.
M· tr×nh:
Option Explicit
Dim i, n As Long

68
§¹i häc Th¸i Nguyªn – Tr−êng §HSP – Khoa To¸n -Tin
LËp tr×nh trªn Windows víi Visual Basic

Private Sub Combo1_Click()


Select Case Combo1.ListIndex
Case 0
File1.Pattern = "*.*"
Case 1
File1.Pattern = "*.TXT"
Case 2
File1.Pattern = "*.DAT"
Case 3
File1.Pattern = "*.REG"
Case 4
File1.Pattern = "*.DOC"
End Select
List1_Change
End Sub

Private Sub Combo2_Click()


Text1.Text = Combo2.Text
End Sub

Private Sub Command1_Click()


If Text2.Text <> "" Then
Dim dd, size As String
If Right(Text1.Text, 1) <> "\" Then
dd = Text1.Text + "\" + Text2.Text
Else
dd = Text1.Text + Text2.Text
End If

size = Str(FileLen(dd))
MsgBox "Size of the File " & Text2.Text & " is "
& size & " Bytes.", , "Open"
Else
MsgBox "You not select a Filename !", , "Open"
End If
End Sub

Private Sub Command2_Click()


Unload Me
End Sub

Private Sub Command5_Click()


MsgBox "Xin lçi b¹n, môc nµy ch−a cµi ®Æt." +
Chr(10) + "Chóng t«i sÏ cµi ®Æt trong thêi gian
tíi.", 48, "Më tÖp"
End Sub

69
§¹i häc Th¸i Nguyªn – Tr−êng §HSP – Khoa To¸n -Tin
LËp tr×nh trªn Windows víi Visual Basic

Private Sub Dir1_Change()


File1.Path = Dir1.Path
Text1.Text = Dir1.Path
List1_Change
Text2.Text = ""
End Sub

Private Sub Drive1_Change()


On Error GoTo DriveError
Dir1.Path = Drive1.Drive
Exit Sub
DriveError:
MsgBox "Drive Error !", 16, "Error"
Drive1.Drive = Dir1.Path
Exit Sub
End Sub

Private Sub File1_Click()


Text2.Text = File1.FileName
End Sub

Private Sub File1_DblClick()


Command1_Click
End Sub

Private Sub Form_Load()


Form1.Show
Form1.Combo1.AddItem "All Files (*.*)"
Form1.Combo1.AddItem "Data Files (*.TXT)"
Form1.Combo1.AddItem "Text Files of Data (*.DAT)"
Form1.Combo1.AddItem "Word Document Files (*.DOC)"
Form1.Combo1.ListIndex = 0
Form1.Text1.Text = Form1.Dir1.Path
List1_Change
End Sub

Private Sub List1_Change()


Form1.List1.Clear
Form1.Text1.Text = Form1.Dir1.Path
n = Form1.File1.ListCount
For i = 0 To n
Form1.List1.AddItem (Form1.File1.List(i))
Next i
End Sub

70
§¹i häc Th¸i Nguyªn – Tr−êng §HSP – Khoa To¸n -Tin
LËp tr×nh trªn Windows víi Visual Basic

Private Sub List1_Click()


Text2.Text = List1.Text
End Sub

Private Sub List1_DblClick()


Command1_Click
End Sub

71

Das könnte Ihnen auch gefallen