您的位置:首页 > 编程语言 > ASP

VB,ASP读写文本文件及读取指定行

2008-09-04 18:27 295 查看
写文本的代码

<%

set myfileobject=server.CreateObject("Scripting.FileSystemObject")

set mytextfile=myfileobject.OpenTextFile(server.MapPath("test.txt"),2,true)

mytextfile.WriteLine("这是一个测试")

mytextfile.WriteLine("这是一个测试")

mytextfile.close

%>

读文本的代码:

<%

set myfileobject=server.createobject("scripting.filesystemobject")

set mytextfile=myfileobject.opentextfile("c:/mydir/test.txt")

while not mytextfile.atendofstream

response.write(mytextfile.readline)

wend

mytextfile.close

%>

上面的读取方式显然有些原始,看下面:

优化后的读取指文本文件定行的函数代码

Function lines(txtpath As String, ByVal startline As Integer, linenum As Integer) As String '显示 txtpath 文件的从startline 行开始的 linenum 行的内容

lines = ""

Dim filetxt As String, x As Variant, i As Integer

filetxt = String(FileLen(txtpath), " ")

Open txtpath For Binary As 1

Get #1, , filetxt

Close 1

x = Split(filetxt, vbCrLf)

'MsgBox UBound(x) + 1 '行数

If startline > UBound(x) Then MsgBox "行溢出", 64, "err!": Exit Function

If startline <= UBound(x) Then

If startline + linenum <= UBound(x) Then

For i = startline To startline + linenum - 1

lines = lines & x(i) & " "

Next

Else

For i = startline To UBound(x)

lines = lines & x(i) & " "

Next

End If: End If

End Function
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: