Writing data to a text file in a format - vb.net

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) & " ~ ")

Related

System.IndexOutOfRangeException: 'Index was outside the bounds of the array.' in datagridview

I'm trying to retrieve data from the web to desktop using vbnet, but whenever i tried to show it on datagridview it show this error.
It only succes when i only show the first column.
But when it comes to add more column it will show at first but have error like this.
And when i tried to run it again it have error like this.
The code i use :
Imports System.Net
Imports System.IO
Public Class Form1
Dim strArr() As String
Dim strArr1() As String
Dim count, c1 As Integer
Dim str, str2 As String
Private Sub DataGridView1_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim k As Integer = 0
Dim uri As New Uri("http://localhost/tampil.php")
If (uri.Scheme = Uri.UriSchemeHttp) Then
Dim request As HttpWebRequest = HttpWebRequest.Create(uri)
request.Method = WebRequestMethods.Http.Get
Dim response As HttpWebResponse = request.GetResponse()
Dim reader As New StreamReader(response.GetResponseStream())
Dim pagehtml As String = reader.ReadToEnd()
response.Close()
str = pagehtml
strArr = str.Split(";")
For count = 0 To strArr.GetUpperBound(0)
ReDim Preserve strArr1(k)
strArr1(k) = strArr(count)
str2 = strArr1(k)
Dim words As String() = strArr1(k).Split(New Char() {"-"c})
If str2 = "" Then
Exit For
End If
DataGridView1.Rows.Add("")
DataGridView1.Rows(DataGridView1.Rows.Count - 2).Cells(0).Value = words(0)
DataGridView1.Rows(DataGridView1.Rows.Count - 2).Cells(1).Value = words(1)
DataGridView1.Rows(DataGridView1.Rows.Count - 2).Cells(2).Value = words(2)
DataGridView1.Rows(DataGridView1.Rows.Count - 2).Cells(3).Value = words(3)
DataGridView1.Rows(DataGridView1.Rows.Count - 2).Cells(4).Value = words(4)
k += 1
Next
End If
End Sub
End Class
Data from web
Can anyone help ?
Adding a row will return the index of the new row.
You can use that when updating the cell values.
This method will add the rows as you'd expect.
If there is any chance of values being returned from the html query that have a different number of elements, you should check that.
Private Sub LoadDataGridViewFromHTML(htmlValue As String)
Dim entities() As String = htmlValue.Split(Convert.ToChar(";"))
For Each entityItem As String In entities
If Not String.IsNullOrEmpty(entityItem) Then 'check you're not dealing with an empty string
Dim entityValues() As String = entityItem.Split(Convert.ToChar("-"))
Dim newRowId As Integer = DataGridView1.Rows.Add("")
DataGridView1.Rows(newRowId).Cells(0).Value = entityValues(0)
DataGridView1.Rows(newRowId).Cells(1).Value = entityValues(1)
DataGridView1.Rows(newRowId).Cells(2).Value = entityValues(2)
DataGridView1.Rows(newRowId).Cells(3).Value = entityValues(3)
DataGridView1.Rows(newRowId).Cells(4).Value = entityValues(4)
End If
Next
End Sub

Type expected error VB.Net

Error ImagePlease assist, I get a "Type expected" error on my code for a windows based application. I get the error on this line "Dim objSW As New StreamWriter(objFS)"
Imports System.IO
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim strFileName As String = My.Application.Info.DirectoryPath & "\empout_fixed.txt"
Dim objFS As New FileStream(strFileName, FileMode.Create, FileAccess.Write)
Dim objSW As New StreamWriter(objFS)
Dim strEmpName As String
Dim intDeptNbr As Integer
Dim strJobTitle As String
Dim dtmHireDate As Date
Dim sngHrlyRate As Single
strEmpName = “Thabo Lereko”
intDeptNbr = 1001
strJobTitle = “Junior Programmer”
dtmHireDate = #10/05/2014#
sngHrlyRate = 99.99
' Write out the record to the file ...
objSW.WriteLine(strEmpName.PadRight(20) &
intDeptNbr.ToString.PadLeft(4) &
Space(5) &
strJobTitle.PadRight(21) &
Format(dtmHireDate, "M/d/yyyy").PadRight(10) &
Format(sngHrlyRate, "Standard").PadLeft(5))
MsgBox("Record was written to the output file.")
objSW.Close()
End Sub
End Class
The problem is that you have named your project "StreamWriter", which causes "StreamWriter" to refer to the namespace of the project. Maybe you should use more a bit more descriptive project names in the future just for clarity?
You can fix this by referring to the real StreamWriter with namespace:
Imports System.IO
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim strFileName As String = My.Application.Info.DirectoryPath & "\empout_fixed.txt"
Using objFS As New FileStream(strFileName, FileMode.Create, FileAccess.Write)
Using objSW As New System.IO.StreamWriter(objFS)
Dim strEmpName As String
Dim intDeptNbr As Integer
Dim strJobTitle As String
Dim dtmHireDate As Date
Dim sngHrlyRate As Single
strEmpName = “Thabo Lereko”
intDeptNbr = 1001
strJobTitle = “Junior Programmer”
dtmHireDate = #10/05/2014#
sngHrlyRate = 99.99
' Write out the record to the file ...
objSW.WriteLine(strEmpName.PadRight(20) &
intDeptNbr.ToString.PadLeft(4) &
Space(5) &
strJobTitle.PadRight(21) &
Format(dtmHireDate, "M/d/yyyy").PadRight(10) &
Format(sngHrlyRate, "Standard").PadLeft(5))
MsgBox("Record was written to the output file.")
End Using
End Using
End Sub
End Class
Ps. Added the using-statements that should always be used with iDisposable-objects. Removed the unnecessary close-call also.

WebClient.DownloadString to work with 2 urls

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

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

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)