使用 VBScript 读取和写入文件 [英] Read and write into a file using VBScript

查看:36
本文介绍了使用 VBScript 读取和写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何使用 VBScript 读取和写入一些字符串到文本文件中?我的意思是我有一个已经存在的文本文件,所以当我使用下面的代码时:-

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 fso = CreateObject("Scripting.FileSystemObject" )            
Set file = fso.OpenTextFile("C:\New\maddy.txt",1,1) 

这只是为了读取而打开文件,但我无法写入任何内容当我使用此代码时:-

This opens the file only for reading but I am unable to write anything and when I use this code:-

Set fso = CreateObject("Scripting.FileSystemObject" )            
Set file = fso.OpenTextFile("C:\New\maddy.txt",2,1)

我只能使用此文件进行写入但无法读取任何内容.无论如何,我们可以通过仅调用一次 OpenTextFile 方法来打开文件进行读写.

I can just use this file for writing but unable to read anything. Is there anyway by which we can open the file for reading and writing by just calling the OpenTextFile method only once.

我真的是 VBScript 的新手.我只熟悉 C 的概念.是否有任何链接可以让我真正开始使用 VBScript?

I am really new to VBScript. I am only familiar with C concepts. Is there any link to really get me started with VBScript?

我想我需要对对象和属性概念有很好的了解.

I guess I need to have a good knowledge of the objects and properties concepts.

推荐答案

您可以创建一个临时文件,然后将其重命名回原始文件:

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 

使用 OpenTextFile 的用法几乎相同:

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 

这篇关于使用 VBScript 读取和写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆