VB操作文本文件的一個(gè)實(shí)例

字號:

這是一個(gè)很有實(shí)際學(xué)習(xí)意義的VB操作文本文件的一個(gè)實(shí)例,學(xué)習(xí)VB的朋友一定要認(rèn)真的看一看。
    \'功能:刪除、替換文本中一行,或者插入內(nèi)容到文本中某一行
    \'作者: soho_andy (冰)
    \'參數(shù):
    \'strSourceFile 原始文件完整名
    \'strTargetFile 生成新文件的完整名
    \'intRow 操作的行數(shù)
    Sub 操作文件中一行(strSourceFile As String, strTargetFile As String, intRow As Long)
    Dim filenum As Integer
    Dim fileContents As String
    Dim fileInfo() As String
    Dim i As Integer
    Dim j As Integer
    filenum = FreeFile
    Open strSourceFile For Binary As #filenum
     fileContents = Space(LOF(filenum))
    Get #filenum, , fileContents
    Close filenum
    fileInfo = Split(fileContents, vbCrLf)
    \'取出源文件行數(shù),按照回車換行來分隔成數(shù)組
    filenum = FreeFile
    If Dir(strTargetFile, vbNormal) <> \"\" Then
    Kill strTargetFile
    End If
    Dim Filestr() As String
    \'刪除一行代碼塊
    Open strTargetFile For Append As #filenum
     \'循環(huán)每一行
    For i = 0 To UBound(fileInfo) - 1
    If i <> intRow - 1 Then
    Print #filenum, fileInfo(i)
    End If
    Next
    Close #filenum
    \'替換一行代碼塊
    Open strTargetFile For Append As #filenum
    \'循環(huán)每一行
    For i = 0 To UBound(fileInfo) - 1
    If i = intRow - 1 Then
    Print #filenum, \"你要替換進(jìn)去的內(nèi)容\"
    End If Next
    Close #filenum
    \'插入一行代碼塊
    Open strTargetFile For Append As #filenum
    \'循環(huán)每一行
    For i = 0 To UBound(fileInfo) - 1
    If i = intRow - 1 Then
    Print #filenum, \"你要插入到這行的內(nèi)容\"
    Print #filenum, fileInfo(i) \'保留原來的行,位置后移一位
    End If
    Next
    Close #filenum
    MsgBox \"完畢\"
    End Sub