当前位置: 移动技术网 > IT编程>脚本编程>VBScript > VBS读取配置文件配置项的实现代码

VBS读取配置文件配置项的实现代码

2020年03月09日  | 移动技术网IT编程  | 我要评论

董先生 大鹏,李先彬,52522

以下是一个读取配置文件的函数:
本函数仅适用于以下格式的配置文件(.ini,.txt,.inf):

[mark1]
key1=key1value
key2=key2value
........
[mark2]
key1=key1value
key2=key2value

核心代码

'************************************************************
'功能:读取配置文件(.ini,.txt格式)的配置项的值,并返回值
'参数:filepath - 配置文件的完整路径
'   mark - 配置开始标记
'   key - 需要获取的配置项名称
'调用方法:ret = getconfig("d:\configure.ini","computer","ip")
'作者:虎肖至尊
'日期:2013-06-20
'************************************************************
function getconfig(filepath,mark,key)
 dim fso, str_readline
 set fso = createobject("scripting.filesystemobject")
 '判断配置文件是否存在
 if fso.fileexists(filepath) then
 '初始化配置标记,默认为未找到
 flag = 0
 '打开配置文件
 set configfile = fso.opentextfile(filepath, 1)
 '循环读取文件数据行
 do
  str_readline = configfile.readline
  wscript.echo str_readline
  '判断读取的数据行是否为空
  if str_readline <> "" then
  '判断读取数据行是否为需要查找的配置开始标记
  if lcase(trim(str_readline))="[" & lcase(mark) & "]" then
   '找到配置开始标记
   flag = 1  
   '循环读取当前配置开始标记下的配置项,直到在当前配置标记下找到所需配置项
   '或下一个配置项开始标记出现时退出
   do
   str_readline = configfile.readline
   retnum = instr(str_readline,"=")
   '检查读取的配置项是否有等号
   if retnum > 0 then
    '判断获取配置项名称是否为所需的配置项
    if trim(lcase(left(str_readline,retnum-1)))= trim(lcase(key)) then
    '获取配置项等号后的数据
    getconfig = trim(right(str_readline,len(str_readline)-retnum))
    '找到后,退出函数
    exit function 
    end if
   end if
   '判断当前是否为下一个配置项开始标记
   if (instr(str_readline,"[")>0 and instr(str_readline,"]")>0) then
    '标记当前配置项开始标记为下一个配置
    flag = 0
    '退出函数
    exit function
   end if
   loop until (flag = 0 or configfile.atendofstream)
  end if
  end if 
 loop until configfile.atendofstream
 '关闭文件
 configfile.close
 set fso = nothing
 else
 '文件未找到,给出提示信息
 msgbox "配置文件"&"[" & filepath &"]不存在,请检查路径是否正确."
 end if
end function

实例:

我们需要读取d:\config\environment.ini文件的[computer2]下的ip项的值,文件内容如下:

[computer1]
computername=computer1
ip=192.168.1.1
[computer2]
computername=computer2
ip=192.168.1.2

使用以上函数即可获取

ip = getconfig("d:\config\environment.ini","computer2","ip")
msgbox ip

好了到这里就完成了.

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网