VBS基础篇 - FileSystemObject对象详解

2019-01-15 19:29:16王冬梅

CopyFile及MoveFile的使用

方法名:CopyFile(source,destination,overwrite)

说明:将一个或多个文件从某位置复制到另一位置。详细说明请见表7

方法名:MoveFile(source,destination)

说明:将 source 指定的一个或多个源文件移动到 destination 指定的目的文件夹。

示例:

Dim sourcepath,targetpath sourcepath = "C:/testing/*.txt" targetpath = "C:/123/" Call FolderAttributes(sourcepath,targetpath) Sub FolderAttributes(sourcepath,targetpath) Dim fso Set fso = CreateObject("Scripting.FileSystemObject") '将testing文件夹下所有扩展名名为.txt的文件,复制到123文件夹下 fso.CopyFile sourcepath,targetpath fso.MoveFile sourcepath,targetpath End Sub

备注:如果C:/123文件夹不存在,则脚本运行时提示“路径不存在”

CreateTextFile及DeleteFile的使用

方法名:CreateTextFile(filename,overwrite,unicode)

说明:创建指定文件并返回 TextStream 对象,该对象可用于读或写创建的文件。

方法名:DeleFile(filespec,force)

说明:删除指定的文件。详细说明请见表7.

示例:

Dim sourcepath sourcepath = "C:/testing/ myClass2.doc " Call FolderAttributes(sourcepath) Sub FolderAttributes(sourcepath) Dim fso Set fso = CreateObject("Scripting.FileSystemObject") '在testing文件夹下,使用CreateTextFile()创建myClass2.doc文件 fso.CreateTextFile sourcepath,true '删除testing文件夹下,所有扩展名为.txt的文件 fso.DeleteFile sourcepath,true End Sub

备注:如果所删除的文件为只读属性且DeleteFile()的参数为false的话,则脚本运行是出现“没有权限”FileExists的使用

方法名:FileExists(filespec)

说明:判断所指定的文件是否存在。此方法将返回Bool值. 详细说明请见表7.

示例:

Dim sourcepath sourcepath = "C:/testing/test.txt" Call FolderAttributes(sourcepath) Sub FolderAttributes(sourcepath) Dim fso Set fso = CreateObject("Scripting.FileSystemObject") '判断C:/testing/test.txt是否有存在,如果存在返回“true”;否则返回“false” If fso.FileExists(sourcepath) Then msgbox "true" else msgbox "false" End If End Sub

GetBaseName、GetFileName及GetExtensionName的使用

方法名:GetBaseName(filespec)

说明:返回字符串,文件 (不带扩展名), 或者提供的路径说明中的文件夹。

方法名:GetExtensionName(filespec)

说明:返回字符串,该字符串包含路径最后一个组成部分的扩展名。

方法名:GetFileName(pathspec)

说明:返回指定路径(不是指定驱动器路径部分)的最后一个文件或文件夹。

示例:

Dim sourcepath sourcepath = "C:/testing/test.txt" Call FolderAttributes(sourcepath) Sub FolderAttributes(sourcepath) Dim fso Set fso = CreateObject("Scripting.FileSystemObject") '返回文件名test, 扩展名 txt, 文件名+扩展名 test.txt Msgbox (fso.GetBaseName(sourcepath)) Msgbox (fso. GetExtensionName(sourcepath)) Msgbox (fso.GetFileName(sourcepath)) End Sub