Find a specific line of text in a text document and insert the next 37 lines of text into a database
Helo, I have an SQL database, and 50 text files, and Visual Basic 2010 Premimum, I need to find a specific line of text in the text files and then take the next 37 lines of text and save them in my database. I need advice as to point me in the right direction. Also if anyone might know o开发者_StackOverflow中文版f a book I can use for future reference it would be greatly appreciated.
Const textToFind As String = "a specific line of text"
Const maxLineCount As Int32 = 37
Dim allLines As New List(Of String)
Dim path As String = "c:\temp\MyTest.txt"
Try
If File.Exists(path) Then
File.Delete(path)
End If
Dim sw As StreamWriter = New StreamWriter(path)
For i As Int32 = 1 To 100
sw.WriteLine("This")
sw.WriteLine("is some text")
sw.WriteLine("to test")
sw.WriteLine("Reading")
sw.WriteLine("a specific line of text")
Next
sw.Close()
Dim sr As StreamReader = New StreamReader(path)
Dim lineCounter As Int32 = 0
Dim lineFound As Int32 = -1
Do While sr.Peek() >= 0
Dim line As String = sr.ReadLine
If lineFound = -1 Then
If line.Equals(textToFind) Then
lineFound = 0
End If
Else
lineCounter += 1
If lineCounter <= maxLineCount Then
allLines.Add(line)
Else
Exit Do
End If
End If
Loop
sr.Close()
' save found lines to the database '
Catch ex As Exception
Console.WriteLine("The process failed: {0}", ex.ToString())
End Try
As for parsing the file, it's easy to search files line-by-line:
Var i = 0
Var foundOnLineNumber = -1
For Each line In File.ReadAllLines("<file name here>")
i = i + 1
If foundOnLineNumber > 0 Then
' Add line to database
Else If <criteria for finding "that" line> Then
foundOnLineNumber = i
End If
Next
I've never been good at VB (I usually do C#, so this might not compile). Try to figure out what criteria you are looking for and replace that in the code above. Here is a list of VB.NET books. Find one that covers ADO or some other database access technology. I think your biggest help will be to simply get a good grasp on the VB language and the facilities that .NET has at its disposal.
精彩评论