---
title: "[QTP]通过vbscript往文本文件中指定位置插入指定内容"
author: "mmdev"
date: "2013-01-25T10:42:00Z"
tags: []
slug: "qtp-vbscript"
draft: false
lastmod: "2013-02-18T12:02:50Z"
id: 1806852
url: "https://mmdev.iteye.com/blog/1806852"
---

'作者：席飞剑

'日期：2013-1-25

'功能：往文本文件中指定位置插入指定内容

'参数：txtFile为需要读取的文件，可以根据需要将以下操作封装成一个函数。

'&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;尝试往文本文件中指定位置插入指定的文本内容&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;

假设："C:\\Users\\xifeijian\\Desktop\\test.txt"存在，并且文件内容为：

111111111  
222222222  
333333333  
444444444

目标：希望在

333333333  
444444444之间插入指定的内容I'm xifeijian

实现：

vbscript没有指针，所以实现这类功能，没有其它高级程序语言那么方便，可以直接seek到某位置，再插入需要的内容，换个思路，可以通过split函数将原内容按标记符进行分组，再拼接也是一个不错的选择：

Const ForReading = 1, ForWriting = 2  
Dim fso, oFile  
txtFile="C:\\Users\\xifeijian\\Desktop\\test.txt"  
Set fso = CreateObject("Scripting.FileSystemObject")  
If fso.FileExists(txtFile) Then  
Set oFile= fso.OpenTextFile(txtFile,ForReading)  
ReadLineTextFile =oFile.ReadLine '读取文件第一行内容  
While oFile.AtEndOfStream = false  
ReadLineTextFile = ReadLineTextFile &vbnewline& oFile.ReadLine '遍历文件其它内容  
wend  
Set oFile= fso.OpenTextFile(txtFile,ForWriting)  
deli1="333333333"'需要插入内容的起始位置  
toAdd1="I'm xifeijian" '需要插入的文本内容  
arr=split(ReadLineTextFile,deli1,-1,1) '按照指定分隔符进行字符串分割，但这里我并未做是否能够找到指定分隔符的异常处理，否则后续使用arr(0)时会报数组越界的。  
ReadLineTextFile=arr(0)&deli1&toAdd1&arr(1)  
' msgbox ReadLineTextFile  
oFile.Write ReadLineTextFile  
oFile.close() '关闭对象  
else  
print "File Not Found"  
End If

Set fso = nothing '释放对象

运行结束后，文本文件的内容则变为：

111111111  
222222222  
333333333I'm xifeijian  
444444444