2012-08-14 11 views
1

텍스트 파일의 특정 줄을 다른 텍스트 파일로 추출하려고합니다. 내가 다음 코드특정 텍스트 파일의 특정 줄을 다른 텍스트 파일로 추출

Imports System.IO 



Public Class Form1 

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 

     Dim Tr As IO.TextReader = System.IO.File.OpenText("C:\Assignment.txt") 
     For c As Integer = 1 To 10 

      If c = 7 Then 
       Dim MyFileLine As String = Split(Tr.ReadToEnd(), vbCrLf)(c) & vbCrLf 
       Tr.Close() 



       Dim TW As System.IO.TextWriter 
       'Create a Text file and load it into the TextWriter 
       TW = System.IO.File.CreateText("C:\Assignment1.txt") 
       TW.WriteLine(MyFileLine) 
       'Flush the text to the file 
       TW.Flush() 
       'Close the File 
       TW.Close() 
      End If 

     Next c 
    End Sub 
End Class 

그러나이 코드 추출물만을 줄 내가 8, 9, 10, 14, 15, 16를 추출 할 아무 7을 사용하고, 또한 라인. 제게 올바른 해결책을 알려주세요. 미리 감사드립니다.

답변

1

여기에 몇 가지 문제가있는 것으로 보입니다. 나는이를 수정 한 후 아래에 설명합니다 :

Imports System.IO 

Public Class Form1 

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 

     Dim currentLine As String 
     Dim lineCounter As Integer = 1 
     Dim lineNumbersRequired As List(Of Integer) = New List(Of Integer) 
     lineNumbersRequired.Add(7) 
     lineNumbersRequired.Add(8) 
     lineNumbersRequired.Add(9) 
     lineNumbersRequired.Add(10) 
     lineNumbersRequired.Add(14) 
     lineNumbersRequired.Add(15) 
     lineNumbersRequired.Add(16) 

     Dim TW As System.IO.TextWriter 
     'Create a Text file and load it into the TextWriter 
     TW = System.IO.File.CreateText("C:\Assignment1.txt") 

     Using Tr As IO.TextReader = New IO.StreamReader("C:\Assignment.txt") 
      While Not Tr.EndOfStream 
       If lineNumbersRequired.Contains(lineCounter) Then 
        Dim MyFileLine As String = Split(currentLine, vbCrLf)(c) & vbCrLf 
        TW.WriteLine(MyFileLine) 
       End If 
       lineCounter = lineCounter + 1 
      End While 
     End Using 

     TW.Flush() 
     'Close the File 
     TW.Close() 

    End Sub 
End Class 

참고 : 코드는 테스트하지,하지만 당신은 몇 가지 오류를 컴파일 얻을 할 경우 아주 가까이해야합니다!

확인 후, 내가 여기에 무슨 짓을했는지 그냥 빠른 개요 : 당신이 있었기 때문에

  1. 은 잠시에 대한 루프를 변경하였습니다 그 다음, 일 때문에 경우에도 1에서 10까지 실행 루프 당신은 당신의 파일에서 10 번째 줄을 읽지 않았을 것입니다. 그래서 TextReader가 파일의 모든 줄을 읽었을 때 끝나는 while 루프로 변경했습니다. 또한 파일에서 읽은 현재 행이 currentLine이라는 새 변수에 추가되었습니다.
  2. 새로운 currentLine 변수가 이제 쓰기 파일의 행을 채우는 데 사용됩니다.
  3. 내가 원하는 라인 번호를 보유 할 Integer리스트를 추가했다. while 루프 내에서 각 라인이 처리 될 때 카운터를 가지며,이 카운터가 라인 번호리스트에 있다면 출력 파일에 저장하려면 현재 행을 출력합니다.

내가 어떻게되는지 알아보고 그 중 하나에 대해 더 많은 설명이 필요하면 질문하십시오.

+0

No .... (현재 줄 = Tr.ReadLine()) 없음 Nothing –

+0

코드를 변경하고 나중에'TextReader '를 지우기 위해'Using' 문을 구현했습니다. 죄송합니다, C#에서 변환! – XN16

+0

좋아, 이제 다른 문제로하자. ,, 특정 HTML 페이지의 특정 줄을 복사하려면 어떤 코드를 써야 하나? –

관련 문제