这是一个场景,我在“FilestoMerge”目录中有一些文本文件。我正在使用VbScript循环遍历目录中的每个文件,并将内容合并到“Output”目录中的一个“output.txt”文件中。之后,合并成功,我想删除原始文件。在删除之前,如何确保父文件中的内容是否已成功写入输出文件。下面是我的Vbscript合并文件。
Set fso = CreateObject("Scripting.FileSystemObject")
set OutputFile = fso.CreateTextFile(strOutputFileName)
Set WMIService = GetObject("winmgmts:\\" & "." & "\root\cimv2")
Set FileList = WMIService.ExecQuery _
("ASSOCIATORS OF {Win32_Directory.Name='C:\Users\xxxx\yyyy\FilesToMerge'} Where " _
& "ResultClass = CIM_DataFile")
For Each file In FileList
Set objTextFile = fso.OpenTextFile(file.Name, ForReading)
strText = objTextFile.ReadAll
objTextFile.Close
OutputFile.WriteLine strText <<<<need to make sure this is successfull, then only delete
fso.DeleteFile(file.Name)
Next
OutputFile.Close
答案 0 :(得分:0)
你可以做一些错误检查:
On Error Resume Next
For Each file In FileList
Set objTextFile = fso.OpenTextFile(file.Name, ForReading)
strText = objTextFile.ReadAll
objTextFile.Close
If Err Then
' There's been an error reading the file
' Handle in some way
Err.Clear ' Clear error
End If
OutputFile.WriteLine strText <<<<need to make sure this is successfull, then only delete
If Err Then
' There's been an error writing the read content to the output file
' Handle in some way
Err.Clear
End If
fso.DeleteFile(file.Name)
Next
On Error GoTo 0
您还可以将读取操作的前三行合并为一行:
strText = fso.OpenTextFile(file.Name, ForReading).ReadAll
无需打开,阅读和关闭,如果你想要做的就是一次性阅读文件的内容。
::编辑::
第二个想到上面的结构会很危险,因为你可能会处理一个读错误,然后继续将变量的内容(由于读错误而为空)写入输出文件,然后删除原始文件,因为写入文件没有错误。所以使用以下结构:
On Error Resume Next
For Each file In FileList
strText = fso.OpenTextFile(file.Name, ForReading).ReadAll
If Err Then
' There's been an error reading the file
' Handle in some way
Err.Clear ' Clear error
Else
OutputFile.WriteLine strText
If Err Then
' There's been an error writing the read content to the output file
' Handle in some way
Err.Clear
Else
fso.DeleteFile(file.Name)
End If
End If
Next
On Error GoTo 0
这只会在没有读取错误的情况下尝试写入文件,并且只有在没有写入OutputFile的错误时才会尝试删除该文件