如何附加到文件的末尾?

时间:2017-01-05 04:34:23

标签: vbscript

我需要一个程序来检查文件以查找来自用户的字符串输入,如果该字符串存在则显示一条消息,但如果它不存在则将其添加到列表中。

这是我到目前为止所做的:

Const ForReading = 1

Dim strSearchFor
strSearchFor = inputbox("What is the url of the song?",,"")

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile("autoplaylist.txt", ForAppending)

do until objTextFile.AtEndOfStream
    strLine = objTextFile.ReadLine()

    If InStr(strLine, strSearchFor) <> 0 then
        Wscript.Echo "That song is already in the list."
    Else


        Wscript.Echo "That song was added to end of list."
    End If
loop
objTextFile.Close

但我不确定如何在文件中添加文字。 它还显示每一行的消息,有3000行。有没有办法解决这个问题?

1 个答案:

答案 0 :(得分:2)

这个怎么样......

Const ForReading = 1
Const ForAppending = 8

Dim strSearchFor, strFileText, strFileName
strSearchFor = inputbox("What is the url of the song?",,"")

Set objFSO = CreateObject("Scripting.FileSystemObject")

strFileName = "autoplaylist.txt"

' Check file exists and ReadAll
' ------------------------------
If objFSO.FileExists(strFileName) Then
    On Error Resume Next

    With objFSO.OpenTextFile(strFileName, ForReading)
        strFileText = .ReadAll
        .Close
    End With

    If Err.Number <> 0 Then
        WScript.Echo "File access error"
        WScript.Quit
    End If

    On Error Goto 0
Else
    Wscript.Echo "File does not exists"
    Wscript.Quit
End If

' Search for input string
' If found append user input
' ----------------------------
If Instr(strFileText, strSearchFor) = 0 Then
    With objFSO.OpenTextFile(strFileName, ForAppending)
        .WriteLine(strSearchFor)
        .Close
    End With
    Wscript.Echo strSearchFor & " was not found in " & strFileName & " and has been appended"
Else
    Wscript.Echo strSearchFor & " has been found in " & strFileName
End If

WScript.Quit