WebClient.DownloadString to work with 2 urls - vb.net

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2
Dim downloader As New WebClient
downloader.Encoding = Encoding.UTF8
Dim mystring As String = downloader.DownloadString("ONE LINK HERE" And "OTHER LINK HERE")
Dim myregex As String = "\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b:\d{2,5}"
Dim source As String = mystring
Dim findme As MatchCollection = Regex.Matches(source, myregex)
For Each mymatch As Match In findme
ListBox1.Items.Add(mymatch)
Next
New here, sorry for bad formatation, all i want to do is download string from 2 urls at same time without errors

Related

How to display a random photo from a folder in a picture box and print out the photo name without extension

I have a folder named "MyPhotos", I want to display a random photo at each time a command button is clicked from "Myphoto" and print out the name of the displayed photo in the form without extension . I'm trying the following code, but still can't get the photo name
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _ System.EventArgs) Handles Button1.Click
Dim DirectoryPath As String = Application.ExecutablePath
Directorypath = DirectoryPath.Substring(0, Directorypath.LastIndexOf("\bin")) & "\MyPhotos"
Dim bm As New Bitmap(GetRandomImageFilePath(Directorypath))
picImage.Image = bm
End Sub
Public Function GetRandomImageFilePath(ByVal folderPath As String) As String
Dim files() As String = Directory.GetFiles(folderPath, "*.jpg")
Dim random As Random = New Random()
Return files(random.Next(0, files.Length))
End Function
Any help please ?
I added this to your button method. All I used was FileInfo to get the details.
Dim finfo As FileInfo = New FileInfo(GetRandomImageFilePath(DirectoryPath))
Dim filename As String = finfo.Name.Replace(finfo.Extension, "")
Dim bm As New Bitmap(finfo.FullName)
picImage.Image = bm
You already have the full path being returned by GetRandomImageFilePath.
If you want just the filename, do this in your calling Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _ System.EventArgs) Handles Button1.Click
Dim DirectoryPath As String = Application.ExecutablePath
Directorypath = DirectoryPath.Substring(0, Directorypath.LastIndexOf("\bin")) & "\MyPhotos"
Dim imagePath as String = GetRandomImageFilePath(Directorypath)
Dim fileInfo as New FileInfo(imagePath)
Dim imageName as String = fileInfo.Name
Dim bm As New Bitmap(imagePath)
picImage.Image = bm
End Sub

Read text file with delimiter

i want to read text file and from the fifth line take only the first column before (;) this my code to browse and read text :
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim OpenFile As New OpenFileDialog
OpenFile.FileName = ""
OpenFile.Filter = "Fichier Texte (*.pnp)|*.pnp"
OpenFile.ShowDialog()
Try
Dim lire As New System.IO.StreamReader(OpenFile.FileName)
RichTextBox1.Text = lire.ReadToEnd
lire.Close()
Catch ex As Exception
End Try
End Sub
End Class
help me please
You could try something like this:
Dim lineYouWantToRead As Int32 = 5
Dim fieldYouWantToRead As Int32 = 1
Dim capturedValue As String = ""
Using fileReader As New FileIO.TextFieldParser(OpenFile.FileName)
fileReader.TextFieldType = FileIO.FieldType.Delimited
fileReader.SetDelimiters(";")
While fileReader.LineNumber <= lineYouWantToRead - 1
Dim currentLine As String() = fileReader.ReadFields()
capturedValue = currentLine(fieldYouWantToRead - 1)
End While
End Using
RichTextBox1.Text = capturedValue
Let us know if that is any help.

Variable 'details' is used before it has been assigned a value.

Variable details is used before it has been assigned a value. What is the problem with details?
Option Explicit On
Imports System.Text
Imports System.IO
Public Class Main
Private SelectedItem As ListViewItem
Dim data As String
Dim strpriority As String
Dim task As String
Dim createdate As String
Dim duedate As String
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click
AddTask.Show()
Me.Hide()
End Sub
Private Sub HistoryToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles HistoryToolStripMenuItem.Click
History.Show()
Me.Hide()
End Sub
Private Sub Main_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim fpath As String
Dim splitdata
fpath = AppDomain.CurrentDomain.BaseDirectory
Dim filepath As String
filepath = fpath & "task.txt"
Dim details As String
details = My.Computer.FileSystem.ReadAllText(filepath)
splitdata = Split(details, vbCrLf)
Dim i As Integer
For i = 0 To UBound(splitdata)
lblTaskName.Items.Add(splitdata(i))
Next
lblTime.Enabled = True
Timer1.Interval = 10
Timer1.Enabled = True
lblDate.Text = DateTime.Now.ToString("dd MMMM yyyy")
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
lblTime.Text = TimeOfDay
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
End
End Sub
Private Sub btnRemove_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRemove.Click
If lblTaskName.SelectedItem = "" Then
MsgBox("Please select a record")
Else
If lblTaskName.Items.Count > 0 Then
If MessageBox.Show("Do you really want to delete this record?", "Delete", MessageBoxButtons.YesNo) = MsgBoxResult.Yes Then
lblTaskName.Items.Remove(lblTaskName.SelectedItem.ToString())
Else
MessageBox.Show("Operation Cancelled")
End If
End If
End If
Try
Dim fpath As String
fpath = AppDomain.CurrentDomain.BaseDirectory
Dim filepath As String
filepath = fpath & "task.txt"
Dim details As String
If lblTaskName.Items.Count > 0 Then
details = lblTaskName.Items(0)
Dim i As Integer
For i = 1 To lblTaskName.Items.Count - 1
details = details & vbCrLf & lblTaskName.Items(i)
Next
End If
My.Computer.FileSystem.WriteAllText(filepath, details, False)
Catch ex As Exception
MsgBox("Values Can't be inserted this time")
End Try
End Sub
Private Function filepaths() As String
Throw New NotImplementedException
End Function
End Class
The problem is in the btnRemove_Click method in this part:
Dim details As String
If lblTaskName.Items.Count > 0 Then
details = lblTaskName.Items(0)
If the condition evaluates to false, the details variable is used before it is initialized, because it is only set in the if block up to now.
I suppose you want to move the following line into the if block to solve the problem:
My.Computer.FileSystem.WriteAllText(filepath, details, False)
Alternatively, you can come up with a default value for details so that it is set in any case. For performance reasons, you can set the default value (e.g. a text or String.Empty) in an else branch:
Dim details As String
If lblTaskName.Items.Count > 0 Then
' ...
Else
details = "Default Value"
End If
You need to think through the flow of your program. Consider this code:
Dim details As String
If lblTaskName.Items.Count > 0 Then
details = lblTaskName.Items(0)
Dim i As Integer
For i = 1 To lblTaskName.Items.Count - 1
details = details & vbCrLf & lblTaskName.Items(i)
Next
End If
My.Computer.FileSystem.WriteAllText(filepath, details, False)
You declare the details variable at the top. Then you check that there is at least 1 item in the lblTaskName control. If that test passes, then you assign the first item to details. But what if that test doesn't pass? What if there are 0 items in the lblTaskName control? In that case, the interior of the If block never runs, and nothing ever gets stored in details. Then in the final line, you try to use the value of the details variable *outside of the If block. This is illegal because it may not have been assigned a value.
Perhaps you meant for that WriteAllText line to be inside of If block? Otherwise, you'll need to add an Else clause to your If statement to handle the case where there are 0 items in lblTaskName.
Aside from that, stylistically speaking, you should prefer to initialize variables at the time of declaration whenever possible. So for example, instead of writing:
Dim fpath As String
Dim splitdata
fpath = AppDomain.CurrentDomain.BaseDirectory
Dim filepath As String
filepath = fpath & "task.txt"
Dim details As String
details = My.Computer.FileSystem.ReadAllText(filepath)
splitdata = Split(details, vbCrLf)
write it as:
Dim fpath As String = AppDomain.CurrentDomain.BaseDirectory
Dim filepath As String = fpath & "task.txt"
Dim details As String = My.Computer.FileSystem.ReadAllText(filepath)
Dim splitdata() As String = Split(details, vbCrLf)
(I'm OCD, so I line up my equals signs. That part is totally optional.)
It doesn't make the code run any faster, but it does make it easier to read! More importantly, it decreases the potential for bugs.

Importing last line of a .csv file

I have a csv file and I need to get the last line only into seperate textboxes.
Imports System.IO
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub btnConditions_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConditions.Click
Using reader As New StreamReader("C:\temp\Apr12log.txt")
Dim line As String = reader.ReadLine()
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
line = reader.ReadLine()
End While
txtDate.Text = CStr(fileDate)
End Using
End Sub
End Class
It only inputs the first line I am not sure how to get the last line only.
example of txtfile
01/04/12,00:00,5.4,80,3.0,4.5,9.6,261,0.0,0.0,1025.0,1.0,16.8,43,4.0,3.8,5.4,0.0,0,0.0
Alternatively, you could use the System.IO.File ReadLines() function, which gives you an enumerable that you can call Last() on.
Private Sub btnConditions_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConditions.Click
Dim line As String = System.IO.File.ReadLines("C:\temp\Apr12log.txt").Last()
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)
txtDate.Text = CStr(fileDate)
End Sub
You're only reading in one line. Instead use ReadToEnd() and then split by a new line, like so:
Dim lines() As String = reader.ReadToEnd().Split(Environment.NewLine)
Then you can move to the last line:
Dim line As String = lines(lines.Length - 1)
You can get what you want with a couple of edits to your existing code:
Shift
While line IsNot Nothing
line = reader.ReadLine()
End While
To just after
Dim line As String = reader.ReadLine()
Add another
Dim line2 As String = Nothing
And insert
line2 = line
Into the While loop, i.e.
While line IsNot Nothing
line2 = line
line = reader.ReadLine()
End While
Now line2 is the last line in the file.
Try this:
Dim lines() As String = File.ReadAllLines("C:\temp\Apr12log.txt")
lastLine = lines(lines.Length - 1)

Writing data to a text file in a format

Im trying to get some particular content from a site and place it in text file. i have used a listbox for loop of urls i want to process and another to see output of data. now i want all data in text file each item seperated by "~" sysmbol.
Exmaple Link i used in my.txt file: http://www.maxpreps.com/high-schools/abbeville-yellowjackets-(abbeville,al)/basketball/previous_seasons.htm
Data expected in text file:
Abbeville High School Basketball Stats ~ Team: Varsity 11-12 ~ Colors: Maroon, Gray, White ....
Imports System.IO.StreamReader
Imports System.Text.RegularExpressions
Imports System.IO
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim abc As String = My.Computer.FileSystem.ReadAllText("C:\Documents and Settings\Santosh\Desktop\my.txt")
Dim pqr As String() = abc.Split(vbNewLine)
ListBox2.Items.AddRange(pqr)
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
For Each item In ListBox2.Items
Dim request As System.Net.HttpWebRequest = System.Net.WebRequest.Create(item)
Dim response As System.Net.HttpWebResponse = request.GetResponse
Dim sr As System.IO.StreamReader = New System.IO.StreamReader(response.GetResponseStream())
Dim rsssource As String = sr.ReadToEnd
Dim r As New System.Text.RegularExpressions.Regex("<h1 id=""ctl00_NavigationWithContentOverRelated_ContentOverRelated_Header_Header"">.*</h1>")
Dim r1 As New System.Text.RegularExpressions.Regex("<span id=""ctl00_NavigationWithContentOverRelated_ContentOverRelated_Header_Mascot"">.*</span>")
Dim r3 As New System.Text.RegularExpressions.Regex("<span id=""ctl00_NavigationWithContentOverRelated_ContentOverRelated_Header_Colors"">.*</span>")
Dim r4 As New System.Text.RegularExpressions.Regex("<span id=""ctl00_NavigationWithContentOverRelated_ContentOverRelated_Header_GenderType"">.*</span>")
Dim r5 As New System.Text.RegularExpressions.Regex("<span id=""ctl00_NavigationWithContentOverRelated_ContentOverRelated_Header_AthleteDirectorGenericControl"">.*</span>")
Dim r6 As New System.Text.RegularExpressions.Regex("<address>.*</address>")
Dim r7 As New System.Text.RegularExpressions.Regex("<span id=""ctl00_NavigationWithContentOverRelated_ContentOverRelated_Header_Phone"">.*</span>")
Dim r8 As New System.Text.RegularExpressions.Regex("<span id=""ctl00_NavigationWithContentOverRelated_ContentOverRelated_Header_Fax"">.*</span>")
Dim matches As MatchCollection = r.Matches(rsssource)
Dim matches1 As MatchCollection = r1.Matches(rsssource)
Dim matches3 As MatchCollection = r3.Matches(rsssource)
Dim matches4 As MatchCollection = r4.Matches(rsssource)
Dim matches5 As MatchCollection = r5.Matches(rsssource)
Dim matches6 As MatchCollection = r6.Matches(rsssource)
Dim matches7 As MatchCollection = r7.Matches(rsssource)
Dim matches8 As MatchCollection = r8.Matches(rsssource)
For Each itemcode As Match In matches
Dim W As New IO.StreamWriter("C:\" & FileName.Text & ".txt")
W.Write(itemcode.Value.Split("""").GetValue(2))
W.Close()
'ListBox1.Items.Add(itemcode.Value.Split("""").GetValue(2))
Next
For Each itemcode As Match In matches1
ListBox1.Items.Add(itemcode.Value.Split("""").GetValue(2))
Next
Next item
End Sub
End Class
Just append it to the end of the Write statement like this.
W.Write(itemcode.Value.Split("""").GetValue(2) & " ~ ")