VBS中FileSystemObject对象详解(完整版)

2019-01-15 19:09:06王旭

方法名:Close()
说明:关闭正在打开的文件
方法名:WriteLine(string)
说明:向文件写入字符串 string(可选)和换行符。
示例:

Dim strPath,strText strPath = "C:/testing.txt" strText = "This is Test !" & vbCrLf & “hello word !” '调用函数 Call CreateFile(strPath,strText) Sub CreateFile(strPath,strText) Dim objFso,objStream '创建FileSystemObject对象 Set objFso = CreateObject("Scripting.FileSystemObject") '使用FileSystemObject对象的CreateTextFile(),来返回一个TextStream对象句柄 Set objStream = objFso.CreateTextFile(strPath,True) '三个Write的意思分别为:在文本中写入字符、写入带换行符的字符、写入3个换行符 objStream.Write(strText) ‘objStream.WriteLine(strText) ‘objStream. WriteBlankLines 3 '关闭TextStream对象 objStream.Close End Sub

Read、ReadAll及ReadLine的使用

方法名:Read(numchars)
说明:从 TextStream 文件中读入指定数目的字符并返回结果字符串。
方法名:ReadAll()
说明:读入全部 TextStream 文件并返回结果字符串。
方法名:ReadLine()
说明:从 TextStream 文件中读入一整行字符(直到下一行,但不包括下一行字符),并返回结果字符串。
示例:

Sub CreateFile(strPath,strText) Dim objFso,objStream '创建FileSystemObject对象 Set objFso = CreateObject("Scripting.FileSystemObject") '使用FileSystemObject对象的CreateTextFile(),来返回一个TextStream对象句柄 Set objStream = objFso.CreateTextFile(strPath,True) '写入字符 objStream.WriteLine(strText) Set objStream = objFso.OpenTextFile(strPath,1,true) msgbox (objStream.ReadLine) 'msgbox (objStream.ReadAll) ' msgbox (objStream.Read(Len(strText))) '关闭TextStream对象 objStream.Close End Sub

Skip、SkipLine的使用

方法名:Skip(numchars)
说明:读取 TextStream 文件时跳过指定数目的字符
方法名:SkipLine()
说明:当读到 TextStream 文件时,跳过下一行。
示例:

Dim strPath,strText strPath = "C:/testing.txt" '调用函数 Call CreateFile(strPath) Sub CreateFile(strPath) Dim objFso,objStream '创建FileSystemObject对象 Set objFso = CreateObject("Scripting.FileSystemObject") '使用FileSystemObject对象的CreateTextFile(),来返回一个TextStream对象句柄 Set objStream = objFso.CreateTextFile(strPath,True) '在文本中写入字符 objStream.Write "This is Test !" & vbCrLf & "hello word !" '以只读的方式打开文件 Set objStream = objFso.OpenTextFile(strPath,1,true) '读取文件时跳过5个字符;或者跳过当前行,读取下一行 objStream.Skip(5) 'objStream.SkipLine '读取文本内容 msgbox objStream.ReadAll '关闭TextStream对象 objStream.Close End Sub

备注:两者的区别是:Skip——跳过指定的几个字符;SkipLine——跳过一行

二、TextStream对象的属性