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

来源:互联网 发布:js给href赋参数值 编辑:程序博客网 时间:2024/04/30 20:17

写文本的代码

 

  1.   <%   
  2.   set   myfileobject=server.CreateObject("Scripting.FileSystemObject")   
  3.   set   mytextfile=myfileobject.OpenTextFile(server.MapPath("test.txt"),2,true)   
  4.   mytextfile.WriteLine("这是一个测试")   
  5.   mytextfile.WriteLine("这是一个测试")   
  6.   mytextfile.close   
  7.   %>   

    
    
读文本的代码:   

  1.   <%   
  2.   set   myfileobject=server.createobject("scripting.filesystemobject")   
  3.   set   mytextfile=myfileobject.opentextfile("c:/mydir/test.txt")   
  4.   while   not   mytextfile.atendofstream   
  5.       response.write(mytextfile.readline)   
  6.   wend   
  7.   mytextfile.close   
  8.   %>

   

 

 

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

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

  1. Function lines(txtpath As StringByVal startline As Integer, linenum As IntegerAs String                           '显示   txtpath   文件的从startline   行开始的   linenum   行的内容
  2.   lines = ""
  3.     Dim filetxt     As String, x       As Variant, i       As Integer
  4.             filetxt = String(FileLen(txtpath), "   ")
  5.             Open txtpath For Binary As 1
  6.             Get #1, , filetxt
  7.             Close 1
  8.             x = Split(filetxt, vbCrLf)
  9.       'MsgBox UBound(x) + 1         '行数
  10.       If startline > UBound(x) Then MsgBox "行溢出", 64, "err!":                   Exit Function
  11.       If startline <= UBound(x) Then
  12.       If startline + linenum <= UBound(x) Then
  13.         For i = startline To startline + linenum - 1
  14.         lines = lines & x(i) & "   "
  15.         Next
  16.         Else
  17.         For i = startline To UBound(x)
  18.         lines = lines & x(i) & "   "
  19.         Next
  20.         End If:     End If
  21.           
  22. End Function