深入Scripting Runtime Library 之一[3]

[入库:2005年8月18日] [更新:2007年3月24日]

本文简介:选择自 technofantasy 的 blog

    sdatecreate = "(未知)"
    resume next
end sub

private sub form_load()
    file1.path = "c:\windows"
end sub

private sub form_unload(cancel as integer)
    set fsosys = nothing
end sub

    四、对于textstream对象的操作
    对于通过vb编程对文本文件进行io操作,一直是一个头疼的问题。如果使用inout$函数一次把打开的文件内容
全部读取到一个字符串中的话,对于某一行的字符串操作就会十分不方便,同时还会有一个字符串不能大于65k而导致
无法读取大文件的问题。而采用line input的方法又丧失了对文件整体操作的方便性。而textstream对象提供了一种
基于流的文件操作方式,使得对文本文件的操作方便了很多。
    利用filesystemobject的createtextfile方法或者openastextstream 方法可以建立一个textstream对象,该
对象包含了文件中的所有内容,可以通过只读、只写和追加方式打开文件。当建立了textstream对象只后,用户就可以
直接对textstream进行操作,从而增加了对文件操作的方便性和安全性。
    下面是一个textstream对象操作的范例。
    首先建立一个新的工程文件,加入rs库,在form1中加入三个commandbuton控件和一个textbox控件,在c:\下建立
一个help.txt的文件,然后在form1中加入以下代码:
option explicit

dim fsofile as new filesystemobject
dim fsotextstream as textstream

private sub command1_click()
    if dir$("c:\help.txt") = "" then
        msgbox ("c:\help.txt文件不存在,程序将退出")
        set fsofile = nothing
        end
    end if
    '打开文件
    set fsotextstream = fsofile.opentextfile("c:\help.txt", forreading)
    text1.text = fsotextstream.readall      '将文件读取到text1中
end sub

private sub command2_click()
    dim fsotexttemp as textstream

    '关闭原来的文件,并建立一个同名的新的文件,将更新的文件流写入到新文件中
    fsotextstream.close
    set fsotextstream = nothing
    set fsotexttemp = fsofile.createtextfile("c:\help.txt", true)
    fsotexttemp.write text1.text
    fsotexttemp.close
    set fsotexttemp = nothing
   
    command1_click
    command2.enabled = false
end sub

private sub command3_click()
    fsotextstream.close
    set fsotextstream = nothing
    set fsofile = nothing
    end
end sub

private sub form_load()
    text1.text = ""
    command1.caption = "打开文件"
    command2.caption = "保存文件"
    command3.caption = "退出"
    command2.enabled = false
end sub

private sub text1_change()
    command2.enabled = true
end sub

本文关键:深入Scripting Runtime Library 之一
  相关方案
Google
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top