使用 vb.net 删除文本文件中的特定行 [英] Delete specific lines in a text file using vb.net

查看:43
本文介绍了使用 vb.net 删除文本文件中的特定行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 VB.Net 删除文本的某些特定行.我在 here 看到了一个解决方案,但它在 VB6 中.问题是,我对 VB6 不是很熟悉.有人可以帮助我吗?这是链接中的代码:

I am trying to delete some specific lines of a text using VB.Net. I saw a solution here however it is in VB6. The problem is, I am not really familiar with VB6. Can somebody help me? This is the code from the link:

Public Function DeleteLine(ByVal fName As String, ByVal LineNumber As Long) _As Boolean
    'Purpose: Deletes a Line from a text file

    'Parameters: fName = FullPath to File
    '            LineNumber = LineToDelete

    'Returns:    True if Successful, false otherwise

    'Requires:   Reference to Microsoft Scripting Runtime

    'Example: DeleteLine("C:\Myfile.txt", 3)
    '           Deletes third line of Myfile.txt
    '______________________________________________________________


    Dim oFSO As New FileSystemObject
    Dim oFSTR As Scripting.TextStream
    Dim ret As Long
    Dim lCtr As Long
    Dim sTemp As String, sLine As String
    Dim bLineFound As Boolean

    On Error GoTo ErrorHandler
    If oFSO.FileExists(fName) Then
        oFSTR = oFSO.OpenTextFile(fName)
        lCtr = 1
        Do While Not oFSTR.AtEndOfStream
            sLine = oFSTR.ReadLine
            If lCtr <> LineNumber Then
                sTemp = sTemp & sLine & vbCrLf
            Else
                bLineFound = True

            End If
            lCtr = lCtr + 1
        Loop

        oFSTR.Close()
        oFSTR = oFSO.CreateTextFile(fName, True)
        oFSTR.Write(sTemp)

        DeleteLine = bLineFound
    End If


ErrorHandler:
    On Error Resume Next
    oFSTR.Close()
    oFSTR = Nothing
    oFSO = Nothing

End Function

推荐答案

Dim delLine As Integer = 10
Dim lines As List(Of String) = System.IO.File.ReadAllLines("infile.txt").ToList
lines.RemoveAt(delLine - 1) ' index starts at 0 
System.IO.File.WriteAllLines("outfile.txt", lines)

这篇关于使用 vb.net 删除文本文件中的特定行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆