Removing certain lines in textbox - vb.net

I have a proxy list, that is like IP:PORT, and what I need to do is remove all the proxies with port numbers of 8080, 80, 431, and 13. I've tried to use a StreamReader to do this, but to no avail, any help guys? Thank you.
My code efforts:
Using reader As New StreamReader(o.FileName())
While Not reader.EndOfStream
Dim line As String = reader.ReadLine()
Dim X As String = line.Contains("8080")
For Each X In NsTextBox1.Text
NsTextBox1.Text = NsTextBox1.Text + X
Exit While
Next
End While
End Using

I recently wrote something that should do the trick nicely, if the proxy list contains 1 IP per line without white space at the end that is.
While not the most optimized code it works pretty well, here's some output of it parsing a list of about 6000 proxies.
You'd use it as such.
IO.File.WriteAllText("C:\ProxyOut.txt", ParseProxyList(IO.File.ReadAllText("C:\ProxyIn.txt"), 8080, 80, 431, 13))
EDIT: oh i just read it was for a textbox, usage should not be that different
TextBoxOut.Text = ParseProxyList(TextBoxIn.Text, 8080, 80, 431, 13))
And the Function itself:
Private Function ParseProxyList(ByVal list As String, ParamArray ports() As Integer)
Dim splitList() As String = list.Split(vbCrLf)
Dim sb As System.Text.StringBuilder = New System.Text.StringBuilder()
Dim outputLinesCount As Integer = 0
For Each line As String In splitList
Dim bContainsPort As Boolean = False
For Each port As Integer In ports
If line.EndsWith(":" & port.ToString) Then
bContainsPort = True
End If
Next
If bContainsPort = False Then
sb.AppendLine(line)
outputLinesCount += 1
End If
Next
MsgBox(splitList.Count.ToString & "->" & outputLinesCount.ToString & " (" & (splitList.Count - outputLinesCount) & " Removed)")
Return sb.ToString
End Function

Related

StreamWriter randomly not outputting last line into file

I'm trying to save a class to a text file and I'm getting mixed results. Half the time the last line of the add is in the file and sometimes not. I've not been able to get a consistent output to the file.
So, I added a debug to show me what was being written just prior to the StreamWriter.Write and it showed the line that I added but it doesn't show up in the file.
^ This line is the last line that isn't being written to the file.
Here's what my code where I save the data looks like:
Private sub SaveMemoUsersFile()
If _memoList is Nothing Then
return
End If
Dim memofile = Path.Combine(Configuration.DataFileLocations, $"{Configuration.CompanyID}ucMemoUsers.txt")
Const quote As String = """"
Const comma As String = ","
Dim both = $"{quote}{comma}{quote}"
Using sw = New StreamWriter(memofile)
For Each memoUsers As MemoUsers In _memoList
Dim sb = New StringBuilder()
sb.Append(quote)
sb.Append(memoUsers.Initials)
sb.Append(both)
sb.Append(memoUsers.EmailAddress)
sb.Append(both)
sb.Append(memoUsers.DelinquentLetterCode)
sb.Append(both)
sb.Append(memoUsers.Description)
sb.Append(quote)
'sb.Append(vbCr)
console.write(sb) <--- shows the last line
sw.WriteLine(sb.ToString()) <--- but doesn't write it to the file
Next
End Using
_memoList = nothing
End sub
Anyone have any suggestions? I'm completely lost as to why this is writing to the file randomly.
Might as well just build your file in the stringbuilder and write it:
Private sub SaveMemoUsersFile()
If _memoList is Nothing Then
return
End If
Dim q = """"
Dim b = $"{q},{q}"
Dim sb = New StringBuilder()
For Each memoUsers As MemoUsers In _memoList
sb.Append(q)
sb.Append(memoUsers.Initials).Append(b)
sb.Append(memoUsers.EmailAddress).Append(b)
sb.Append(memoUsers.DelinquentLetterCode).Append(b)
sb.Append(memoUsers.Description).AppendLine(q)
Next
Dim memofile = Path.Combine(Configuration.DataFileLocations, $"{Configuration.CompanyID}ucMemoUsers.txt")
IO.File.WriteAllText(memoFIle, sb.ToString())
_memoList = nothing
End sub

Sort text file with delimiter

I have a text file that is 800KB line by line with comma delimiter.
I am trying to sort this text file by the first part which is a date.
when I run this it takes about 2 seconds to complete.
something is really slowing it down, what do you guys see?
Dim sw As New Stopwatch
sw.Start()
Dim sMilli As Integer = 1000
Dim iSortedDates As New SortedDictionary(Of Date, String)
For Each line As String In IO.File.ReadAllLines(iFilePath)
Dim eachPart() As String = line.Split(","c)
Dim eachDate As Date = Date.Parse(eachPart(0)).AddMilliseconds(sMilli)
iSortedDates(eachDate) = line
If sMilli = 5000 Then sMilli = 1
sMilli += 1
Next
Dim iAllData As String = ""
For Each iSNew In iSortedDates.Keys
iAllData += iSortedDates(iSNew) & Environment.NewLine
Next
IO.File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory & iFilePath, iAllData)
sw.Stop()
Debug.Print("Total Milliseconds: " & sw.Elapsed.TotalMilliseconds)
If you are targeting version 4 or higher of the Framework, you may be able to save some time by using IO.File.ReadLines instead of IO.File.ReadAllLines as ReadLines doesn't make you wait until the whole file is read before you can start processing the lines.
You can avoid building that long iAllData string one line at a time by using iSortedDates.Values to create an array that can be written bi IO.File.WriteAllLines.
Dim sw As New Stopwatch
sw.Start()
Dim sMilli As Integer = 1000
Dim iSortedDates As New SortedDictionary(Of Date, String)
For Each line As String In IO.File.ReadLines(iFilePath)
Dim eachPart() As String = line.Split(","c)
Dim eachDate As Date = Date.Parse(eachPart(0)).AddMilliseconds(sMilli)
iSortedDates(eachDate) = line
If sMilli = 5000 Then sMilli = 1
sMilli += 1
Next
Dim iAllData() As String = iSortedDates.Values.ToArray
IO.File.WriteAllLines(AppDomain.CurrentDomain.BaseDirectory & iFilePath, iAllData)
sw.Stop()
Debug.Print("Total Milliseconds: " & sw.Elapsed.TotalMilliseconds)
I would look into Linq if you could. Below is a quick query I have done for you, it not only reads all of the lines, but it checks if the split string is a date then order by that and put anything else at the end sorted. I tested this on a 6.73 MB file and came out at 1.97 seconds. If you ask me that is really quick I would say.
You can use this anywhere
Dim nDate As Date
Dim lines As List(Of String) = System.IO.File.ReadAllLines(yourfile).Where(Function(x) Date.TryParse(x.Split(","c)(0), nDate) OrElse Not String.IsNullOrEmpty(x)).OrderBy(Function(line) line.Split(",")(0)).ToList
IO.File.WriteAllText("FILE LOCATION", Concat(lines))
Function to return all lines in a string
Public Shared Function Concat(source As List(Of String)) As String
Dim sb As New System.Text.StringBuilder
For Each s As String In source
sb.AppendLine(s)
Next
Return sb.ToString()
End Function
P.S. Sorry if the Linq query looks long, you can make that top down so it can be easier to read if you want.

VB "Index was out of range, must be non-negative and less than the size of the collection." When trying to generate a random number more than once

So I'm trying to generate a random number on button click. Now this number needs to be between two numbers that are inside my text file with various other things all separated by the "|" symbol. The number is then put into the text of a textbox which is being created after i run the form. I can get everything to work perfectly once, but as soon as i try to generate a different random number it gives me the error: "Index was out of range, must be non-negative and less than the size of the collection." Here is the main code as well as the block that generates the textbox after loading the form. As well as the contents of my text file.
Private Sub generate()
Dim newrandom As New Random
Try
Using sr As New StreamReader(itemfile) 'Create a stream reader object for the file
'While we have lines to read in
Do Until sr.EndOfStream
Dim line As String
line = sr.ReadLine() 'Read a line out one at a time
Dim tmp()
tmp = Split(line, "|")
rows(lineNum).buybutton.Text = tmp(1)
rows(lineNum).buyprice.Text = newrandom.Next(tmp(2), tmp(3)) 'Generate the random number between two values
rows(lineNum).amount.Text = tmp(4)
rows(lineNum).sellprice.Text = tmp(5)
rows(lineNum).sellbutton.Text = tmp(1)
lineNum += 1
If sr.EndOfStream = True Then
sr.Close()
End If
Loop
End Using
Catch x As Exception ' Report any errors in reading the line of code
Dim errMsg As String = "Problems: " & x.Message
MsgBox(errMsg)
End Try
End Sub
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
rows = New List(Of duplicate)
For dupnum = 0 To 11
'There are about 5 more of these above this one but they all have set values, this is the only troublesome one
Dim buyprice As System.Windows.Forms.TextBox
buyprice = New System.Windows.Forms.TextBox
buyprice.Width = textbox1.Width
buyprice.Height = textbox1.Height
buyprice.Left = textbox1.Left
buyprice.Top = textbox1.Top + 30 * dupnum
buyprice.Name = "buypricetxt" + Str(dupnum)
Me.Controls.Add(buyprice)
pair = New itemrow
pair.sellbutton = sellbutton
pair.amount = amounttxt
pair.sellprice = sellpricetxt
pair.buybutton = buybutton
pair.buyprice = buypricetxt
rows.Add(pair)
next
end sub
'textfile contents
0|Iron Sword|10|30|0|0
1|Steel Sword|20|40|0|0
2|Iron Shield|15|35|0|0
3|Steel Shield|30|50|0|0
4|Bread|5|10|0|0
5|Cloak|15|30|0|0
6|Tent|40|80|0|0
7|Leather Armour|50|70|0|0
8|Horse|100|200|0|0
9|Saddle|50|75|0|0
10|Opium|200|500|0|0
11|House|1000|5000|0|0
Not sure what else to add, if you know whats wrong please help :/ thanks
Add the following two lines to the start of generate():
Private Sub generate()
Dim lineNum
lineNum = 0
This ensures that you don't point to a value of lineNum outside of the collection.
I usually consider it a good idea to add
Option Explicit
to my code - it forces me to declare my variables, and then I think about their initialization more carefully. It helps me consider their scope, too.
Try this little modification.
I took your original Sub and changed a little bit take a try and let us know if it solve the issue
Private Sub generate()
Dim line As String
Dim lineNum As Integer = 0
Dim rn As New Random(Now.Millisecond)
Try
Using sr As New StreamReader(_path) 'Create a stream reader object for the file
'While we have lines to read in
While sr.Peek > 0
line = sr.ReadLine() 'Read a line out one at a time
If Not String.IsNullOrEmpty(line) And Not String.IsNullOrWhiteSpace(line) Then
Dim tmp()
tmp = Split(line, "|")
rows(lineNum).buybutton.Text = tmp(1)
rows(lineNum).buyprice.Text = rn.Next(CInt(tmp(2)), CInt(tmp(3))) 'Generate the random number between two values
rows(lineNum).amount.Text = tmp(4)
rows(lineNum).sellprice.Text = tmp(5)
rows(lineNum).sellbutton.Text = tmp(1)
lineNum += 1
End If
End While
End Using
Catch x As Exception ' Report any errors in reading the line of code
Dim errMsg As String = "Problems: " & x.Message
MsgBox(errMsg)
End Try
End Sub

Reading an unknown string from a Text Box

I've got a text box which works as a console (in a form application).
I'd like to run a certain sub when the user types in:
broadcast blabla
the sub would broadcast the string blabla.
How would the program recognize ONLY the first word?
Would something like this work?
If ConsoleInput.Text = "broadcast " & command Then
BroadcastMessage(command)
End If
You can use String.Split:
Dim words As String() = ConsoleInput.Text.Split({" "c}, StringSplitOptions.RemoveEmptyEntries)
If words.Length > 1 AndAlso words(0).ToLower() = "broadcast" Then
BroadcastMessage(words(1))
End If
Edit: If you want to broadcast all words it might be better to use String.Substring:
Dim spaceIndex = ConsoleInput.Text.IndexOf(" "c)
If spaceIndex > -1 Then
Dim firstWord = ConsoleInput.Text.Substring(0, spaceIndex)
If firstWord.ToLower = "broadcast" Then
broadcast(ConsoleInput.Text.Substring(spaceIndex + 1))
End If
End If

get local IPv4 of computer using VB.net

I'm trying to get the ip address of my local PC, and one one of my other PCs it gets the v4 address fine, but on this one the code:
Dns.GetHostEntry(Dns.GetHostName).AddressList(0).ToString()
returns what I guess is a IPv6 address:
fe80::9c09:e2e:4736:4c62%11
How do I get the IPv4 address?
Disclaimer- I don't have IPv6 installed and there is probably a much better way to do this, but what does the following return:
Dns.GetHostEntry(Dns.GetHostName()).AddressList
.Where(a => !a.IsIPv6LinkLocal && !a.IsIPv6Multicast && !a.IsIPv6SiteLocal)
.First()
.ToString();
Edit - didn't notice you were asking in VB, so I've tried translating it to:
Dim s As String = Dns.GetHostEntry(Dns.GetHostName()).AddressList _
.Where(Function(a As IPAddress) Not a.IsIPv6LinkLocal AndAlso Not a.IsIPv6Multicast AndAlso Not a.IsIPv6SiteLocal) _
.First() _
.ToString()
This may blow up, so don't treat it as production code.
Here's my solution for getting a routable IPv4 IP without using an external service:
Function GetLocalIP() As String
Dim IPList As System.Net.IPHostEntry = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName)
For Each IPaddress In IPList.AddressList
'Only return IPv4 routable IPs
If (IPaddress.AddressFamily = Sockets.AddressFamily.InterNetwork) AndAlso (Not IsPrivateIP(IPaddress.ToString)) Then
Return IPaddress.ToString
End If
Next
Return ""
End Function
Function IsPrivateIP(ByVal CheckIP As String) As Boolean
Dim Quad1, Quad2 As Integer
Quad1 = CInt(CheckIP.Substring(0, CheckIP.IndexOf(".")))
Quad2 = CInt(CheckIP.Substring(CheckIP.IndexOf(".") + 1).Substring(0, CheckIP.IndexOf(".")))
Select Case Quad1
Case 10
Return True
Case 172
If Quad2 >= 16 And Quad2 <= 31 Then Return True
Case 192
If Quad2 = 168 Then Return True
End Select
Return False
End Function
Note that my code is also verifying that the range is routable (IsPrivateIP). You can remove or modify that part if you are looking for something else.
I used a combined Cmd/Visual Basic code and it worked :
Dim ResString As String = "result.txt"
If File.Exists("result.txt") Then
File.Delete("result.txt")
End If
Shell("cmd.exe /c cd " & Application.StartupPath & " && ipconfig >> " & ResString & "&& exit", AppWinStyle.NormalFocus)
Dim Ipv4 As String
Dim Ipv4Found As Boolean = False
Dim Ipv4Char As Integer = 43
Dim Ipv4Str As String
Threading.Thread.Sleep(1500)
'Wait some seconds to create "result.txt"
Dim Ipv4Reader As StreamReader
Ipv4Reader = File.OpenText("result.txt")
Do Until Ipv4Found = True
Ipv4Str = Ipv4Reader.ReadLine()
If Not Ipv4Str = Nothing Then
If Ipv4Str.Contains("IPv4") Then
Try
Ipv4 = Ipv4Str.Chars(Ipv4Char)
Do Until Ipv4Char = 60
Ipv4Char = Ipv4Char + 1
Ipv4 = Ipv4 & Ipv4Str.Chars(Ipv4Char)
'Read results step by step
Loop
Catch ex As Exception
End Try
MsgBox("Your IPv4 Address is " & Ipv4)
Ipv4Found = True
Ipv4Reader.Close()
End If
Else
End If
Loop
If your computer language is english you may have some unusual characters in the IPv4 String ( My pc is actually in Italian )
I think you should use this:
Dim tmpHostName As String = System.Net.Dns.GetHostName()
myIPaddress = System.Net.Dns.GetHostByName(tmpHostName).AddressList(0).ToString()
GetHostByName is obsolete but this is the way to get the IPv4. Why? Because the getbyhostname function is created before IPv6 so the function get only the IPv4 connection, not the fe80::9c09:e2e:4736:4c62%11.
Something maybe fun is this little function that'll show all IP addresses on your computer:
Public Function getOwnIp() As String
Dim hostIP As IPHostEntry = Dns.GetHostEntry(Dns.GetHostName())
Dim position As Integer = 0
Dim ip As String = Nothing
While ipList < hostIP.AddressList.Length
ip += hostIP.AddressList(position).ToString & vbCrLf
position += 1
End While`enter code here`
Return ip
End Function
I was looking for the answer to this question myself and I could not find one suitable to my needs. I managed to experiment with various answers across the net until I came up with this (works great!). Just thought I would share since this post is the top result via Google.
''''Routine to fetch IPv4 Network addresses for all local network interfaces.
Dim adapters As NetworkInterface() = NetworkInterface.GetAllNetworkInterfaces()
Dim adapter As NetworkInterface
For Each adapter In adapters
Dim properties As IPInterfaceProperties = adapter.GetIPProperties()
If properties.UnicastAddresses.Count > 0 Then
For Each unicastadress As UnicastIPAddressInformation In properties.UnicastAddresses
Dim ip As IPAddress = unicastadress.Address
If ip.AddressFamily = AddressFamily.InterNetwork Then
ComboBox1.Items.Add(ip.ToString)
End If
Next unicastadress
End If
Next adapter
You first need to import the system namespace into your application and then create an instance of the System.Net.NetworkInformation.IPAddressInformation and use it as such
Example
Imports system.data.sqlclient
imports system
Public class Form1
Dim IPAdd As System.Net.NetworkInformation.IPAddressInformation
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
MsgBox("My IP Address is " & IPAdd.Address.ToString)
End Sub
End Class
Dim localIp As IPHostEntry = Dns.GetHostEntry(Dns.GetHostName())
txtLocal.Text = localIp.AddressList(1).ToString
Notice that I changed the (0) index to (1).
This one works on my side
Dim IPaddressList = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList
Dim IPaddrPC As String = ""
For Each item In IPaddressList
If item.AddressFamily = Net.Sockets.AddressFamily.InterNetwork Then
IPaddrPC = item.Address.ToString
Exit For
End If
Next