2014-05-20 108 views
2

我想使用VB.Net刪除一些文本的特定行。我看到一個解決方案here但是它在VB6中。問題是,我不太熟悉VB6。有人能幫助我嗎? 這是從鏈接代碼:使用vb.net刪除文本文件中的特定行

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 
+0

如何大是包含要刪除的行的文件? – Steve

+0

大約1KB到2KB。 – svynsaenz

+0

然後從@大衛的回答下面是最好的一個 – Steve

回答

5
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) 
+0

謝謝!我只需要爲代碼添加一個'For'循環。 – svynsaenz

0

或者您可以使用

TEXTFILE = TextFile.Replace( 「你想刪除」, 「」)

+1

這會留在你的文件中的空行。您需要刪除整個行,包括換行符。 – HuH

+0

然後它會'TEXTFILE = TextFile.Replace( 「你想刪除」,vbNewLine,B,1,將b.length - 1)',在此之前加上'昏暗b以字符串()=斯普利特(TextBox1.Text ,vbNewLine)'。沒有測試它,但它應該工作,它用-1行代替每個「你想刪除」。 –

1
'This can also be the file that you read in 
    Dim str As String = "sdfkvjdfkjv" & vbCrLf & "dfsgkjhdfj" & vbCrLf & "dfkjbhhjsdbvcsdhjbvdhs" & vbCrLf & "dfksbvashjcvhjbc" 

    Dim str2() As String = str.Split(vbCrLf) 

    For Each s In str2 
     If s.Contains("YourString") Then 
      'add your line to txtbox 
     Else 
      'don't add your line to txtbox 
     End If 
    Next 
+0

這幫了我,謝謝! <3 –

相關問題