---
title: "[QTP]通过vbscript读取一个文件中的所有内容"
author: "mmdev"
date: "2013-01-24T09:58:00Z"
tags: []
slug: "qtp-vbscript"
draft: false
lastmod: "2013-02-18T12:02:51Z"
id: 1806853
url: "https://mmdev.iteye.com/blog/1806853"
---

'作者：席飞剑

'日期：2013-1-23

'功能：读取文件中的所有内容并输出（这是一个很常用的功能）

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

'&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&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;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;

Const ForReading = 1, ForWriting = 2  
Dim fso, oFile  
txtFile="C:\\Users\\jiffy\\Desktop\\电台.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  
oFile.close() '关闭对象  
else  
print "File Not Found"  
End If

Set fso = nothing '释放对象

msgbox ReadLineTextFile

PS：其它高级编程语言实现此功能方法类似，对于高级程序语言，例如C#，可以通过StreamReader对象进行读取，一直ReadToEnd即可：

string strPath = System.Web.HttpContext.Current.Server.MapPath(FilePath);  
StreamReader sr = new StreamReader(FilePath, System.Text.Encoding.Default);  
StringBuilder sb = new StringBuilder();  
sb.Append(sr.ReadToEnd());  
sr.Close();