Read and write into a file using VBScript

前端 未结 9 1472
轮回少年
轮回少年 2020-11-27 06:34

How can we read and write some string into a text file using VBScript? I mean I have a text file which is already present so when I use this code below:-

Set         


        
9条回答
  •  萌比男神i
    2020-11-27 07:15

    You can create a temp file, then rename it back to original file:

    Set objFS = CreateObject("Scripting.FileSystemObject")
    strFile = "c:\test\file.txt"
    strTemp = "c:\test\temp.txt"
    Set objFile = objFS.GetFile(strFile)
    Set objOutFile = objFS.CreateTextFile(strTemp,True)
    Set ts = objFile.OpenAsTextStream(1,-2)
    Do Until ts.AtEndOfStream
        strLine = ts.ReadLine
        ' do something with strLine 
        objOutFile.Write(strLine)
    Loop
    objOutFile.Close
    ts.Close
    objFS.DeleteFile(strFile)
    objFS.MoveFile strTemp,strFile 
    

    Usage is almost the same using OpenTextFile:

    Set objFS = CreateObject("Scripting.FileSystemObject")
    strFile = "c:\test\file.txt"
    strTemp = "c:\test\temp.txt"
    Set objFile = objFS.OpenTextFile(strFile)
    Set objOutFile = objFS.CreateTextFile(strTemp,True)    
    Do Until objFile.AtEndOfStream
        strLine = objFile.ReadLine
        ' do something with strLine 
        objOutFile.Write(strLine & "kndfffffff")
    Loop
    objOutFile.Close
    objFile.Close
    objFS.DeleteFile(strFile)
    objFS.MoveFile strTemp,strFile 
    

提交回复
热议问题