从文本文件中删除a中的每个第2行和第3行

时间:2011-06-23 13:02:51

标签: text-files line

我目前正在寻找一种删除txt文件中每(n)行和第(n)行的方法。 例如,每隔2和5行。 有没有办法用脚本或C#?

1 个答案:

答案 0 :(得分:0)

这段代码是在VB.NET中,但我相信这会做你想要的吗?

    Dim sr As streamreader = Nothing
    Dim sw As StreamWriter = Nothing
    Dim LineString As String = ""
    Dim LineNum As Integer = 0
    Try
        sr = New StreamReader("C:\scratch\input.txt")
        sw = New StreamWriter("c:\scratch\output.txt")
        Do Until sr.EndOfStream
            LineString = sr.ReadLine
            LineNum += 1

            If LineNum Mod 2 = 0 Then
                'don't output 2nd line
            ElseIf LineNum Mod 5 = 0 Then
                'don't output 5th line
            Else
                'write it 
                sw.WriteLine(LineString)
            End If
        Loop
    Catch ex As Exception
        MsgBox("Error - " & ex.Message)
    Finally
        If Not IsNothing(sr) Then sr.Close()
        If Not IsNothing(sw) Then sw.Close()
    End Try