order by date in txt file using vb.net - vb.net

i made a program that takes release date and title from IMDB api and saves them in them in .txt file...can i order them by date somehow
Imports System.IO
Imports System.Xml.Linq
Imports System.Text.RegularExpressions
Public Class Form1
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim _reg As Regex = New Regex("http://www.imdb.com/title/([A-Za-z0-9\-]+)/*?", _
RegexOptions.IgnoreCase)
Dim value As String = TextBox1.Text
Dim m As Match = _reg.Match(value)
If (m.Success) Then
Dim key As String = m.Groups(1).Value
Dim url As String = "http://mymovieapi.com/?id=" + key + "&type=xml&plot=none&episode=0&lang=en-US&aka=simple&release=simple&business=0&tech=0"
Dim Document As XDocument = XDocument.Load(url)
Dim title = Document.Root.Element("title").Value()
Dim releaseDate = Date.ParseExact(Document.Root.Element("release_date").Value,
"yyyyMMdd", System.Globalization.CultureInfo.InstalledUICulture)
TextBox2.Text = "Release Date: " & releaseDate & " / Title: " & title
Else : TextBox2.Text = "Please use IMDB links"
End If
Button2.Enabled = True
End Sub
Private Sub Button2_Click_1(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Dim Writer As System.IO.StreamWriter
Writer = New System.IO.StreamWriter("C:\Users\Azer\Documents\Movies.txt", True)
Writer.Write(TextBox2.Text & vbCrLf)
Writer.Close()
Button2.Enabled = False
End Sub
Private Sub Button4_Click(sender As System.Object, e As System.EventArgs) Handles Button4.Click
Dim Reader As System.IO.StreamReader
Reader = New System.IO.StreamReader("C:\Users\Azer\Documents\Movies.txt")
Dim tempstring As String
Do
tempstring = Reader.ReadLine()
TextBox3.Text = TextBox3.Text + tempstring + vbCrLf
Loop Until tempstring = ""
Reader.Close()
End Sub
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
Me.Close()
End Sub
Private Sub Button5_Click(sender As System.Object, e As System.EventArgs) Handles Button5.Click
TextBox3.Clear()
End Sub
End Class

As David said, a database would make this a lot easier. However, if you can't use a database (or have some other reason for doing it this way), here's one way to approach it.
Make a small class that holds the information (to make it easier to sort, like this:
Public Class MovieInfo
Public Property As DateTime
Public Title As String
End Class
Next, read the current file (if it exists) and populate a List<MovieInfo> with the data in it.
Dim movies As String() = File.ReadAllLines("C:\Users\Azer\Documents\Movies.txt")
Dim movieParts = From m in movies
Select m.Split(New String() { "/", ":" }, StringSplitOptions.RemoveEmptyEntries)
Dim parsedDate As DateTime
Dim movieData As List(Of MovieInfo) = (From mi In movieParts
Select New MovieInfo With
{
.ReleaseDate = _
If(DateTime.TryParseExact(mi(1).Trim, "dd.MM.yyyy", _
System.Globalization.CultureInfo.InvariantCulture, _
System.Globalization.DateTimStyle.None, _
parsedDate), parsedDate, DateTime.MinValue),
.Title = mi(3).Trim()
}.ToList()
Essentially the code above reads the text file into an array (one line per element), and then using LINQ splits each line into 4 parts based on : and /. Then it takes the result of that query and builds a List of MovieInfo, with the date string converted to DateTime for easy sorting.
The DateTime.TryParseExact takes an input string of the specified format (in this case, dd.MM.yyyy) and if possible converts it to a DateTime object. If it's successful, it returns true and the DateTime value is in the parsedDate variable. If it's not true, I use the MinValue for DateTime for the ReleaseDate property of the MovieInfo class.
After that, you'll get the new data from your API call and add it to the List of MovieInfo (you'll probably want to eliminate any duplicates). Since you didn't post the format of the data from the API, it's rather hard for me to give you a code sample to parse it, but in a nutshell you can build a second list of MovieInfo objects and then merge the existing and new list together.
Then you sort the List of MovieInfo and overwrite the original text file. Something like this should do the trick:
movieData.Sort(Function(x, y) y.ReleaseDate.CompareTo(x.ReleaseDate))
Dim output As New StringBuilder()
For Each info As MovieInfo in movieData
output.Append("Release Date: ")
output.Append(info.ReleaseDate.ToString("dd.MM.yyyy"))
output.Append(" / Title: ")
output.Append(info.Title)
output.Append(Enviroment.NewLine)
Next
File.WriteAllText("C:\Users\Azer\Documents\Movies.txt", output.ToString())
This code sorts the list with a lambda expression to put the movies in date order (newest to oldest). It then uses a StringBuilder with a For Each loop to build the output, and then writes it to the file (overwriting the file if it already exists).
Note that if you reverse the x and the y in the Sort, you'll get oldest to newest by date.

Dim allLines As String() = File.ReadAllLines("your file name")
System.Array.Sort(allLines)
IO.File.WriteAllLines("your file name", allLines) 'assuming you want to write the file

Related

Search through text file and return a line of text

I am trying to create a program that will search a text file for a line of text and then return the full line of information.
Example line: Joe Blogs JBL 1234
Search: Joe Blogs
Search returns: Joe Blogs JBL 1234
To make it as simple as possible, I have 2 text boxes & 1 button.
Textbox1 = search
Textbox2 = Search results
Button = Search button
Can anyone tell me how to do this because I'm finding it really difficult. I'm new to VB coding so the simplest of code would be helpful!
This is what I have so far:
Imports System.IO
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' Input Text Error
If TextBox1.TextLength = 0 Then
MsgBox("Please enter a Staff Name or Staff Code", MsgBoxStyle.Information, "Error")
End If
'Perform Search
Dim strText As String = SearchFile("F:\Documents\Documents\Visual Studio 2015\Projects\ExtentionLocator\ExtentionLocator\Extentionlist.txt", TextBox1.Text)
If strText <> String.Empty Then
TextBox2.Text = strText
End If
End Sub
'Search Function
Public Shared Function SearchFile(ByVal strFilePath As String, ByVal strSearchTerm As String) As String
Dim sr As StreamReader = New StreamReader(strFilePath)
Dim strLine As String = String.Empty
Try
Do While sr.Peek() >= 0
strLine = String.Empty
strLine = sr.ReadLine
If strLine.Contains(strSearchTerm) Then
sr.Close()
Exit Do
End If
Loop
Return strLine
Catch ex As Exception
Return String.Empty
End Try
End Function
'Clear Button
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
TextBox2.Text = ""
TextBox1.Text = ""
End Sub
' Open The text file
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Process.Start("C:\Users\kylesnelling\Documents\Visual Studio 2015\Projects\ExtentionLocator\ExtentionLocator\Extentionlist.txt")
End Sub
End Class
Whenever I perform a search, all I get back is the last line of the text file... does anyone know why?
As Alex B has stated in comments, line If strLine.Contains("textbox1.text") should be If strLine.Contains(strSearchTerm)
Also you are not passing in the search item to the function. The below line you have passed in the string textbox1.text as a string rather than the text inside the textbox. Hence why you never find the line you are searching for and always returns the last record of your file.
Dim strText As String = SearchFile("F:\Documents\Documents\Visual Studio 2015\Projects\ExtentionLocator\ExtentionLocator\Extentionlist.txt", "textbox1,text")
This line should be:
Dim strText As String = SearchFile("F:\Documents\Documents\Visual Studio 2015\Projects\ExtentionLocator\ExtentionLocator\Extentionlist.txt", textbox1.text)
Also with this line Dim sr As StreamReader = New StreamReader("F:\Documents\Documents\Visual Studio 2015\Projects\ExtentionLocator\ExtentionLocator\Extentionlist.txt") why have you used the same path destination when you have already passed in this file location in the variable strFilePath.
line should be Dim sr As StreamReader = New StreamReader(strFilePath)
Its best to use the variables being passed into the function otherwise this function won't be very useful to other parts of code that may be referencing it or if search terms or filepaths change.
Updated from comments:
strLine.ToUpper.Contains(strSearchTerm.ToUpper) this line will make both text uppercase and the word you are searching for to uppercase, which will allow them to ignore case sensitivity, so for example, "text" can match with "Text" by both being converted to "TEXT" when used to compare.
Give this a try friend.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim searchResult As String = SearchFile("F:\Documents\Documents\Visual Studio 2015\Projects\ExtentionLocator\ExtentionLocator\Extentionlist.txt", _
"text to search for")
Me.TextBox2.Text = searchResult
End Sub
Public Shared Function SearchFile(ByVal strFilePath As String, ByVal strSearchTerm As String) As String
Dim fs As New System.IO.StreamReader(strFilePath)
Dim currentLine As String = String.Empty
Try
Dim searchResult As String = String.Empty
Do While fs.EndOfStream = False
currentLine = fs.ReadLine
If currentLine.IndexOf(strSearchTerm) > -1 Then
searchResult = currentLine
Exit Do
End If
Loop
Return searchResult
Catch ex As Exception
Return String.Empty
End Try
End Function

transfering fixed words in multiline textbox in visual basic to seperate single line textboxes

I am having problem in visual basic textbox so my actual problem is i have a Multiline textbox1 containing FirstName="JOHN" in one line and LastName="SMITH" in the newline and i want to transfer only JOHN in separate singleline textbox2 and SMITH in other singleline textbox3.
i want this to happen on click of copy button.
The lefthanside of the textbox1 like FirstName,LastName remains constant whereas the rightside like JOHN,SMITH are changing in nature.
I have created a separate function and i have tried so far as
Public Class Form1
Dim itemsInTextBox As String() = TextBox1.Text.Split(vbCrLf.ToCharArray, StringSplitOptions.RemoveEmptyEntries)
Dim firstName As String = itemsInTextBox(0).Split("=".ToCharArray)(1)
Dim secondName As String = itemsInTextBox(1).Split("=".ToCharArray)(1)
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
TextBox2.Text = firstName
TextBox3.Text = secondName
End Sub
End Class
here's the link to screenshot of what i want to accomplish.
http://tinypic.com/r/2mcev5w/8
Thanks in advance
I think you could separate the text from the textbox by new lines. Something like:
Dim itemsInTextBox as String() = TextBox1.Text.Split(vbCrLf.toCharArray, StringSplitOptions.RemoveEmptyEntries)
Dim firstName as String = itemsInTextBox(0).Split("=".toCharArray)(1)
Dim secondName as String = itemsInTextBox(1).Split("=".toCharArray)(1)
This is assuming your lines in the textbox are separated by new lines. If it is separated by something else, just put that in the split method. This also keeps the quotation marks (do you want this?)
EDIT: for setting other textboxes
TextBox2.Text = firstName
TextBox3.Text = secondName
EDIT2: You have to create those variables on button click. If you do it globally, it will be run before your TextBox1 exists.
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim itemsInTextBox As String() = TextBox1.Text.Split(vbCrLf.ToCharArray, StringSplitOptions.RemoveEmptyEntries)
Dim firstName As String = itemsInTextBox(0).Split("=".ToCharArray)(1)
Dim secondName As String = itemsInTextBox(1).Split("=".ToCharArray)(1)
TextBox2.Text = firstName
TextBox3.Text = secondName
End Sub
Your sample and your description are different. In your sample you use FIRSTNAME=JOHN and in your description you use first-name="john" which are very different.
Lets use your sample. Your test should look like this.
TextBox2.Text = GetValue("FIRSTNAME=JOHN" & vbcrlf & "LASTNAME=SMITH")
TextBox3.Text = GetValue("FIRSTNAME=JOHN" & vbcrlf & "LASTNAME=SMITH")
Of you try it like this, you will see it's not returning the right information.
You'll have to split each line and then split these line again with the = sign like you did.
Function GetValue(ByVal data As String, ByVal key As String) As String
Dim lines() As String = data.Split(Chr(10))
For Each line As String In lines
line = line.Trim()
Dim subData() As String = line.Split("="c)
If subData(0) = key Then
Return subData(1)
End If
Next
Return ""
End Function
Sub Main()
Dim data As String
data = "FIRSTNAME=JOHN" & Environment.NewLine & "LASTNAME=SMITH"
Console.WriteLine(GetValue(data, "FIRSTNAME"))
Console.WriteLine(GetValue(data, "LASTNAME"))
Console.ReadLine()
End Sub
Just move the declaration of the itemsList into the sub for the copy.
EDIT: Also need to move the declaration of the strings
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim itemsInTextBox As String() = TextBox1.Text.Split(vbCrLf.ToCharArray, StringSplitOptions.RemoveEmptyEntries)
Dim firstName As String = itemsInTextBox(0).Split("=".ToCharArray)(1)
Dim secondName As String = itemsInTextBox(1).Split("=".ToCharArray)(1)
TextBox2.Text = firstName
TextBox3.Text = secondName
End Sub

How to filter file names by date/time?

I need help in filtering specific time/dates(all files are in .jpeg format) in my program's report generation (motion detection system) in which the user can view detected images from a specific point of time to another (e.g. 1:00pm - 2:00pm) then display the files in the listbox.
sample screenshot filename: pic_HHMMss_ddMMMyyyy
The system works like this. After a motion is detected by the webcam, it automatically captures an image and save it to C:\Surveillance System\Detected and generate the filename pic_HHMMss_ddMMMyyyy. So this is now the report generation form wherein the authorized person can view detected images by filtering the time/date of which when the photo is captured.
For now, I can only display all the files in the directory without any filters. Any insights or help is greatly appreciated. Thanks! :)
codes:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' make a reference to a directory
Dim di As New IO.DirectoryInfo("c:\Surveillance System\Detected")
Dim diar1 As IO.FileInfo() = di.GetFiles()
Dim dra As IO.FileInfo
'list the names of all files in the specified directory
For Each dra In diar1
ListBox1.Items.Add(dra)
Next
End Sub
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
PictureBox1.Image = Image.FromFile("C:\Surveillance System\Detected\" & ListBox1.Text)
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
DateTimePicker2.Format = DateTimePickerFormat.Time
DateTimePicker2.ShowUpDown = True
DateTimePicker1.Format = DateTimePickerFormat.Time
DateTimePicker1.ShowUpDown = True
End Sub
button1_click = show detected
button2_click = clear items
There are two ways to do this. One is by the time listed as part of the file name:
Function GetFiles(ByVal FilterStart As DateTime, ByVal FilterEnd As DateTime) As IEnumerable(Of String)
Dim culture As CultureInfo = CultureInfo.InvariantCulture
Dim FormatString As String = "HHmmss_ddMMMyyyy"
Return Directory.EnumerateFiles("c:\Surveillance System\Detected") _
.Where(Function(f)
Dim Filedate As DateTime = DateTime.ParseExact(f.Replace("pic_", "").Replace(".jpeg", ""), FormatString, culture)
Return Filedate >= FilterStart AndAlso Filedate <= FilterEnd
End Function)
End Function
Update:
I see you changed the picture. The format string provided here only supports original file name format used in the original picture. The new picture shows multiple conventions for the file name format. If you are really going to have multiple kinds of names for your files, you should consider using the Created Date option below, or extend this option to use the TryParseExact() overload that accepts an array of possible formats.
The other is to use the Created Date information from the file system:
Function GetFiles(ByVal FilterStart As DateTime, ByVal FilterEnd As DateTime) As IEnumerable(Of String)
Dim di As New DirectoryInfo("c:\Surveillance System\Detected")
Return di.EnumerateFileSystemInfos() _
.Where(Function(f) f.CreationTime >= FilterStart AndAlso f.CreationTime <= FilterEnd) _
.Select(Function(f) f.Name)
End Function
Try using GetAttributes on your files
see http://msdn.microsoft.com/en-us/library/system.io.file.getattributes(v=vs.110).aspx
EDIT
This will add files created between the two times you set in your DateTimePicker. This will work if you want filter on when the file was created, otherwise you need to do some text transformations to dra.FileName to match it to your filenames. You would also want to add an event to track changes in the DateTimePickers so your list will automatically filter and update
'list the names of all files in the specified directory
For Each dra In diar1
If dra.CreationTime > DateTimePicker1.Value And dra.CreationTime < DateTimePicker2.Value Then
ListBox1.Items.Add(dra)
End If
Next
If you want use the filename then you need to the extract date and convert the text to date so you can file based on the DateTimePicker
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
DateTimePicker_ValueChanged(sender,Nothing)
End Sub
Private Sub DateTimePicker_ValueChanged(sender As System.Object, e As System.EventArgs) Handles DateTimePicker1.ValueChanged, DateTimePicker2.ValueChanged
Dim di As New IO.DirectoryInfo("c:\Surveillance System\Detected")
Dim diar1 As IO.FileInfo() = di.GetFiles()
Dim dra As IO.FileInfo
ListBox1.Items.Clear()
'list the names of all files in the specified directory
For Each dra In diar1
'Get file name and then convert to time
Dim splitname As String() = Replace(dra.Name.ToString, ".jpeg", "").Split("_")
Dim filetime As DateTime = Date.ParseExact(splitname(2) & splitname(1), "ddMMMyyyyHHmmss", System.Globalization.DateTimeFormatInfo.InvariantInfo)
If filetime > DateTimePicker1.Value And filetime < DateTimePicker2.Value Then
ListBox1.Items.Add(dra)
End If
Next
end Sub

Reading from and manipulating a .csv file

I have multiple .csv files for each month which go like:
01/04/2012,00:00,7.521527,80.90972,4.541667,5.774305,7,281.368
02/04/2012,00:00,8.809029,84.59028,6.451389,5.797918,7,274.0764
03/04/2012,00:00,4.882638,77.86806,1.152778,15.13611,33,127.6389
04/04/2012,00:00,5.600694,50.35417,-3.826389,15.27222,33,40.05556
The format is : Date in the form dd/mm/yy,Current time,Current temperature,Current humidity,Current dewpoint,Current wind speed,Current wind gust,Current wind bearing
The program needs to calculate the average for
temperature
humidity
wind speed
wind direction
and display them on a text box.
any ideas?
Here is what I have done so far...
Option Strict On
Option Explicit On
Imports System.IO
Imports System
Public Class Form1
Private Sub cmb1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmb1.SelectedIndexChanged
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnexit.Click
Me.Close()
End Sub
Private Sub btn1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btndata.Click
'This is for August
If cmb1.SelectedIndex = 1 Then
TextBox1.Clear()
Using reader As New StreamReader("c://temp/DailyAug12log.csv")
Dim line As String = reader.ReadLine()
Dim avgTemp As Integer
Dim fields() As String = line.Split(",".ToCharArray())
Dim fileDate = CDate(fields(0))
Dim fileTime = fields(1)
Dim fileTemp = fields(2)
Dim fileHum = fields(3)
Dim fileWindSpeed = fields(4)
Dim fileWindGust = fields(5)
Dim fileWindBearing = fields(6)
While line IsNot Nothing
counter = counter + 1
line = reader.ReadLine()
End While
avgTemp = CInt(fields(2))
avgTemp = CInt(CDbl(avgTemp / counter))
TextBox1.Text = TextBox1.Text & "Month = August" & vbCrLf & "Temperature Average: " & avgTemp & vbCrLf
End Using
End If
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim files() As String
files = Directory.GetFiles("C:\Temp", "*.csv", SearchOption.AllDirectories)
For Each FileName As String In files
cmb1.Items.Add(FileName.Substring(FileName.LastIndexOf("\") + 1, FileName.Length - FileName.LastIndexOf("\") - 1))
Next
End Sub
End Class
Private Class Weather
Public SampleTimeStamp AS Date
Public Temperature AS Double
Public Humidity As Double
Public WindSpeed AS Double
Public WindBearing AS Double
End Class
Sub Main
Dim samples = ReadFile("c://temp/DailyAug12log.csv")
Dim avgTemperature = samples.Average(Function(s) s.Temperature)
...
End Sub
Private Function ReadFile(ByVal fileName as String) AS List(Of Weather)
Dim samples As New List(Of Weather)
Using tfp As new TextFieldParser(filename)
tfp.Delimiters = new String() { "," }
tfp.TextFieldType = FieldType.Delimited
While Not tfp.EndOfData
Dim fields = tfp.ReadFields()
Dim sample As New Weather()
sample.SampleTimeStamp = Date.ParseExact(fields(0) & fields(1), "dd\/MM\/yyyyHH\:mm", CultureInfo.InvariantCulture)
sample.Temperature = Double.Parse(fields(2), CultureInfo.InvariantCulture)
sample.Humidity = Double.Parse(fields(3), CultureInfo.InvariantCulture)
sample.WindSpeed = Double.Parse(fields(4), CultureInfo.InvariantCulture)
sample.WindBearing = Double.Parse(fields(5), CultureInfo.InvariantCulture)
samples.Add(sample)
End While
Return samples
End Using
End Function
I would not use a this aprroach - if the order of the columns changes, your program will show wrong results.
I would use a good csv reader like http://kbcsv.codeplex.com/ and read the Data to a datatable. then you can calculate your resulting columns quite easily and reliablly, because you can adress each column like MyDatatable.Cooumns["Headername"].

How to read a specific line from a text file in VB

I am creating a program that is supposed to write text into a text file, and should be able to read specific lines from a text file in VB (so if i needed to read a specific name I could select line 5 and it would display in the textbox). I am able to read the text from the text file but I do not know how to control a specific line.
Here is my code:
Public Class Form1
Private Sub btnSubmit_Click(sender As System.Object, e As System.EventArgs) Handles btnSubmit.Click
Dim writer As New System.IO.StreamWriter("/text.txt", True)
writer.WriteLine(txtFirstName.Text)
writer.WriteLine(txtLastName.Text)
writer.WriteLine("-------------------------------------")
writer.Close()
End Sub
Private Sub btnRead_Click(sender As System.Object, e As System.EventArgs) Handles btnRead.Click
Dim reader As New System.IO.StreamReader("/text.txt")
Dim FirstName, LastName As String
FirstName = reader.ReadLine()
LastName = reader.ReadLine()
reader.Close()
txtFirstName.Text = FirstName
txtLastName.Text = LastName
End Sub
Private Sub btnClear_Click(sender As System.Object, e As System.EventArgs) Handles btnClear.Click
txtFirstName.Clear()
txtLastName.Clear()
End Sub
End Class
Any help would be appreciated. Thanks!
You will have to read all lines up to the one you're interested in. For example:
Function ReadLineWithNumberFrom(filePath As String, ByVal lineNumber As Integer) As String
Using file As New StreamReader(filePath)
' Skip all preceding lines: '
For i As Integer = 1 To lineNumber - 1
If file.ReadLine() Is Nothing Then
Throw New ArgumentOutOfRangeException("lineNumber")
End If
Next
' Attempt to read the line you're interested in: '
Dim line As String = file.ReadLine()
If line Is Nothing Then
Throw New ArgumentOutOfRangeException("lineNumber")
End If
' Succeded!
Return line
End Using
End Function
This is because lines of text are variable-length records, and there is no way to guess the exact file offset where a specific line begins — not without an index.
If you frequently need to load a specific line, you have some more options:
Load the complete text file into memory, e.g. by using File.ReadAllLines("Foobar.txt"). This returns a String() array which you can access by line number directly.
Create a line number index manually. That is, process a text file line by line, and fill a Dictionary(Of Integer, Integer) as you go. The keys are line numbers, and the values are file offsets. This allows you to .Seek right to the beginning of a specific line without having to keep the whole file in memory.
Try this:
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim reader As New System.IO.StreamReader("C:\text.txt")
Dim allLines As List(Of String) = New List(Of String)
Do While Not reader.EndOfStream
allLines.Add(reader.ReadLine())
Loop
reader.Close()
txtFirstName.Text = ReadLine(5, allLines)
txtLastName.Text = ReadLine(6, allLines)
End Sub
Public Function ReadLine(lineNumber As Integer, lines As List(Of String)) As String
Return lines(lineNumber - 1)
End Function
If you had a file with this:
Line 1
Line 2
Line 3
Line 4
My Name
My LastName
your name textbox will have 'My Name' and your LastName textbox will have 'My LastName'.
This is very simple, try this:
Dim strLineText As String
Dim intLineNumber As Integer
LineNumber=3
myLine = File.ReadAllLines("D:\text.txt").ElementAt(LineNumber).ToString
Yet another option
Private Function readNthLine(fileAndPath As String, lineNumber As Integer) As String
Dim nthLine As String = Nothing
Dim n As Integer
Try
Using sr As StreamReader = New StreamReader(fileAndPath)
n = 0
Do While (sr.Peek() >= 0) And (n < lineNumber)
sr.ReadLine()
n += 1
Loop
If sr.Peek() >= 0 Then
nthLine = sr.ReadLine()
End If
End Using
Catch ex As Exception
Throw
End Try
Return nthLine
End Function
i tried this and it works fine. using VB Express
content inside test.txt:
line1
line2
1
John
then in the form i add
textbox1
textbox2
label1
label2
and a button.
code inside the button:
Private Sub Button2_Click_1(sender As Object, e As EventArgs) Handles Button2.Click
Dim myLine As String
Dim lineNumber0 As Integer
lineNumber0 = 0
Dim lineNumber1 As Integer
lineNumber1 = 1
Dim lineNumber2 As Integer
lineNumber2 = 2
Dim lineNumber3 As Integer
lineNumber3 = 3
TextBox1.Text=File.ReadAllLines("D:\test.txt").ElementAt(lineNumber0).ToString
TextBox2.Text=File.ReadAllLines("D:\test.txt").ElementAt(lineNumber1).ToString
Label1.Text = File.ReadAllLines("D:\test.txt").ElementAt(lineNumber2).ToString
Label2.Text = File.ReadAllLines("D:\test.txt").ElementAt(lineNumber3).ToString
End Sub
Here's a simple but effective solution:
Dim Reader As String = System.IO.File.ReadAllLines("C:\File.txt")(1)
MsgBox("Line 1: " + Reader)
The MsgBox should show the first line of C:\File.txt.