1,写文本文件
Const ForReading = 1, ForWriting = 2
Dim fso, f
set fso=createobject("scripting.filesystemobject")
set f=fso.opentextfile("c:\testfile.txt",ForWriting,true)
f.write "hello"
f.write "world"
f.writeblanklines 2 ‘第二行写入空白行
f.writeline "worldhello"
f.writeline "end" ’写入并换行
f.close
2.读文本文件
Const ForReading = 1, ForWriting = 2
Dim fso, f
set fso=createobject("scripting.filesystemobject")
set f=fso.opentextfile("c:\testfile.txt",ForReading)
readlinefile=f.readline '读取一行
readfileindex=f.read(5) ’读取5个字符
readskipfile=f.ship(3) ‘跳过3个字符开始读取
readskipfile2=f.read(2)’从第四个字符开始读取2个字符
readallfile=f.readall ‘读取所有字符
’f.skipline
readsecondline=f.readline ‘读取第二行
f.colse
3.其他相关属性
Const ForReading = 1
Dim fso, theFile, retstring
Set fso = CreateObject("Scripting.FileSystemObject")
Set theFile = fso.OpenTextFile("c:\testfile.txt", ForReading, False)
Do While theFile.AtEndOfStream<> True ‘判断是不是文件流的结尾
retstring = theFile.ReadLine ‘循环读取每一行
Loop
theFile.Close
ReadEntireFile = retstring
Const ForReading = 1
Dim fso, theFile, retstring
Set fso = CreateObject("Scripting.FileSystemObject")
Set theFile = fso.OpenTextFile(filespec, ForReading, False)
Do While theFile.AtEndOfLine<> True 判断是否行结尾
retstring = theFile.Read(1) ’循环读取没一个字符
Loop
theFile.Close
Const ForReading = 1
Dim fso, theFile, lines
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filespec, ForReading, False)
f.readall
lines=f.line ’返回行数
columns=f.column ‘返回列数,即最长一行的字符个数
另一种打开文件对象的方法
Function TextStreamTest
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Const TristateUseDefault = -2, TristateTrue = -1, TristateFalse = 0
Dim fso, f, ts
Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.GetFile("c:\test1.txt")
Set ts =f.OpenAsTextStream(ForWriting,TristateUseDefault)
ts.Write "Hello World"
‘可写world,但读取时出现乱码
ts.Close
Set ts =f.OpenAsTextStream(ForReading,TristateUseDefault)
TextStreamTest = ts.ReadLine
ts.Close
End Function
'创建文件
Sub CreateAfile
Dim fso, MyFile
Set fso = CreateObject("Scripting.FileSystemObject")
Set MyFile = fso.CreateTextFile("c:\testfile.txt",True)
MyFile.WriteLine("This is a test.")
MyFile.Close
End Sub
'copy、move、delete操作
Dim fso, MyFile
Set fso = CreateObject("Scripting.FileSystemObject")
Set MyFile = fso.GetFile("c:\testfile.txt")
MyFile.Copy ("c:\windows\desktop\test2.txt")
MyFile.move ("c:\windows\desktop\test2.txt")
MyFile.delete