Read and write into a file using VBScript

前端 未结 9 1496
轮回少年
轮回少年 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条回答
  •  醉话见心
    2020-11-27 07:10

    Find more about the FileSystemObject object at http://msdn.microsoft.com/en-us/library/aa242706(v=vs.60).aspx. For good VBScript, I recommend:

    • Option Explicit to help detect typos in variables.
    • Function and Sub to improve readilbity and reuse
    • Const so that well known constants are given names

    Here's some code to read and write text to a text file:

    Option Explicit
    
    Const fsoForReading = 1
    Const fsoForWriting = 2
    
    Function LoadStringFromFile(filename)
        Dim fso, f
        Set fso = CreateObject("Scripting.FileSystemObject")
        Set f = fso.OpenTextFile(filename, fsoForReading)
        LoadStringFromFile = f.ReadAll
        f.Close
    End Function
    
    Sub SaveStringToFile(filename, text)
        Dim fso, f
        Set fso = CreateObject("Scripting.FileSystemObject")
        Set f = fso.OpenTextFile(filename, fsoForWriting)
        f.Write text
        f.Close
    End Sub
    
    SaveStringToFile "f.txt", "Hello World" & vbCrLf
    MsgBox LoadStringFromFile("f.txt")
    

提交回复
热议问题