How to save all items listed on listbox with my.settings - vb.net

I Try to save all the items from a list box with MY.SETTINGS
And Retrieved again on load
But it seems i made an error but i cannot figure out what.
its give 2 error
This is the errors
Error 3 'itemmd5' is not a member of 'MediaAdsAntivirus.My.MySettings'.
Error 2 'myitems' is not a member of 'MediaAdsAntivirus.My.MySettings'.
For this errors i just figure out i forgot to add it on settings
but now i just have a new error
This Is My New Error
Error 2 Value of type 'System.Windows.Forms.ListBox.ObjectCollection' cannot be converted to 'String'.
And i need to load them on loadfrom
How Can I List All Items Again In To It
This Is My Code:
Imports System.IO
Imports System.Security
Imports System.Security.Cryptography
Imports System.Text
Imports System.Net
Public Class form15
Dim md5hashindexer = 1
Dim md5namesave = "Hashes"
#Region "Atalhos para o principal hash_generator função"
Function md5_hash(ByVal file_name As String)
Return hash_generator("md5", file_name)
End Function
Function sha_1(ByVal file_name As String)
Return hash_generator("sha1", file_name)
End Function
Function sha_256(ByVal file_name As String)
Return hash_generator("sha256", file_name)
End Function
#End Region
Function hash_generator(ByVal hash_type As String, ByVal file_name As String)
Dim hash
If hash_type.ToLower = "md5" Then
hash = MD5.Create
ElseIf hash_type.ToLower = "sha1" Then
hash = SHA1.Create()
ElseIf hash_type.ToLower = "sha256" Then
hash = SHA256.Create()
Else
MsgBox("Type de hash inconnu : " & hash_type, MsgBoxStyle.Critical)
Return False
End If
Dim hashValue() As Byte
Dim fileStream As FileStream = File.OpenRead(file_name)
fileStream.Position = 0
hashValue = hash.ComputeHash(fileStream)
Dim hash_hex = PrintByteArray(hashValue)
fileStream.Close()
Return hash_hex
End Function
Public Function PrintByteArray(ByVal array() As Byte)
Dim hex_value As String = ""
Dim i As Integer
For i = 0 To array.Length - 1
hex_value += array(i).ToString("X2")
Next i
Return hex_value.ToLower
End Function
Private Sub BT_Parcourir_Click(sender As System.Object, e As System.EventArgs) Handles BT_Parcourir.Click
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim path As String = OpenFileDialog1.FileName
TB_path.Text = path
LB_md5.Text = md5_hash(path)
LB_sha1.Text = sha_1(path)
LB_sha256.Text = sha_256(path)
ListBox1.Items.Add(LB_md5.Text)
ListBox1.SelectedIndex += 1
Dim itemmd5 = LB_sha256.Text
Dim itemname = md5namesave + md5hashindexer
For Each line As String In ListBox1.Items
itemmd5 = My.Settings.myitems
My.Settings.itemmd5 = ListBox1.Items
Next
End If
End Sub
Private Sub LB_sha256_Click(sender As Object, e As EventArgs) Handles LB_sha256.Click
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs)
End Sub
Private Sub form15_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
End Class

I finally decide to save in txt file and load The data again from it
This Is The Working Code
Imports System.IO
Imports System.Security
Imports System.Security.Cryptography
Imports System.Text
Imports System.Net
Public Class form15
Dim md5hashindexer = 1
#Region "Atalhos para o principal hash_generator função"
Function md5_hash(ByVal file_name As String)
Return hash_generator("md5", file_name)
End Function
Function sha_1(ByVal file_name As String)
Return hash_generator("sha1", file_name)
End Function
Function sha_256(ByVal file_name As String)
Return hash_generator("sha256", file_name)
End Function
#End Region
Function hash_generator(ByVal hash_type As String, ByVal file_name As String)
Dim hash
If hash_type.ToLower = "md5" Then
hash = MD5.Create
ElseIf hash_type.ToLower = "sha1" Then
hash = SHA1.Create()
ElseIf hash_type.ToLower = "sha256" Then
hash = SHA256.Create()
Else
MsgBox("Type de hash inconnu : " & hash_type, MsgBoxStyle.Critical)
Return False
End If
Dim hashValue() As Byte
Dim fileStream As FileStream = File.OpenRead(file_name)
fileStream.Position = 0
hashValue = hash.ComputeHash(fileStream)
Dim hash_hex = PrintByteArray(hashValue)
fileStream.Close()
Return hash_hex
End Function
Public Function PrintByteArray(ByVal array() As Byte)
Dim hex_value As String = ""
Dim i As Integer
For i = 0 To array.Length - 1
hex_value += array(i).ToString("X2")
Next i
Return hex_value.ToLower
End Function
Private Sub BT_Parcourir_Click(sender As System.Object, e As System.EventArgs) Handles BT_Parcourir.Click
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim path As String = OpenFileDialog1.FileName
TB_path.Text = path
LB_md5.Text = md5_hash(path)
LB_sha1.Text = sha_1(path)
LB_sha256.Text = sha_256(path)
ListBox1.Items.Add(LB_md5.Text)
ListBox1.SelectedIndex += 1
Dim itemmd5 = LB_sha256.Text
'For Each line As String In ListBox1.Items
'My.Settings.itemsmd5 = itemmd5
'md5hashindexer += 1
'Next
End If
Dim sb As New System.Text.StringBuilder()
For Each o As Object In ListBox1.Items
sb.AppendLine(o)
Next
System.IO.File.WriteAllText("c:\checkedfilesmd5.txt", sb.ToString())
End Sub
Private Sub LB_sha256_Click(sender As Object, e As EventArgs) Handles LB_sha256.Click
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs)
End Sub
Private Sub form15_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim lines() As String = IO.File.ReadAllLines("c:\checkedfilesmd5.txt")
ListBox1.Items.AddRange(lines)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim sb As New System.Text.StringBuilder()
For Each o As Object In ListBox1.Items
sb.AppendLine(o)
Next
System.IO.File.WriteAllText("c:\checkedfilesmd5.txt", sb.ToString())
MsgBox("Dados Guardados")
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim lines() As String = IO.File.ReadAllLines("c:\checkedfilesmd5.txt")
ListBox1.Items.AddRange(lines)
End Sub
Private Sub Label6_Click(sender As Object, e As EventArgs) Handles Label6.Click
ListBox1.Items.Clear()
End Sub
Private Sub Label7_Click(sender As Object, e As EventArgs) Handles Label7.Click
MsgBox("Atençao Voce Vai Apagar Todos Os Dados Ja Escaneados")
ListBox1.Items.Clear()
System.IO.File.Delete("c:\checkedfilesmd5.txt")
End Sub
End Class

Related

Remove duplicate characters from strings and find the shortest

I can not figure out how to select from the result or the shortest line itself or its number
(Yes, the solution is needed in such ancient operators)
Imports System.IO
Public Class Form1
Sub readputh(ByRef s As String)
s = ""
OpenFileDialog1.Filter = "Textfiles (*.txt)|*.txt"
OpenFileDialog1.ShowDialog()
Do While s = ""
s = OpenFileDialog1.FileName
Loop
End Sub
Sub writeputh(ByRef s As String)
s = ""
SaveFileDialog1.Filter = "Textfiles (*.txt)|*.txt"
SaveFileDialog1.ShowDialog()
Do While s = ""
s = SaveFileDialog1.FileName
Loop
End Sub
Sub ch(ByVal Str As String, ByRef Res As String)
Dim a As Char
Res = Mid(Str, 1, 1)
For i = 2 To Len(Str)
a = CChar(Mid(Str, i, 1))
If InStr(Res, a) = 0 Then
Res = Res + a
End If
Next
End Sub
Sub resh(ByVal filename1 As String, ByVal filename2 As String, ByRef lb1 As ListBox, ByRef lb2 As ListBox)
Dim rf As StreamReader
Dim wf As StreamWriter
Dim s1, s2, s3 As String
s2 = ""
s3 = ""
Try
rf = New StreamReader(filename1)
wf = New StreamWriter(filename2, True)
Do While Not rf.EndOfStream()
s1 = rf.ReadLine()
lb1.Items.Add(s1)
ch(s1, s2)
wf.WriteLine(s2)
lb2.Items.Add(s2)
Loop
wf.Close()
rf.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim filename1, filename2 As String
readputh(filename1)
writeputh(filename2)
resh(filename1, filename2, ListBox1, ListBox2)
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
End
End Sub
End Class
Input file:
youtubeyoutubeyotube
dogdogdogdog
geeksforgeeks
Output file:
youtbe
dog
geksfor
But I expect Output file of only "dog"
I just couldn't handle the old code. One based functions? No! You can translate it back it you want but output is now dog.
Private Function GetOpenPath() As String
OpenFileDialog1.Filter = "Textfiles (*.txt)|*.txt"
If OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
Return OpenFileDialog1.FileName
Else
Return Nothing
End If
End Function
Private Function GetSavePath() As String
SaveFileDialog1.Filter = "Textfiles (*.txt)|*.txt"
If SaveFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
Return SaveFileDialog1.FileName
Else
Return Nothing
End If
End Function
Private Function ch(ByVal Str As String) As String
Dim a As Char
Dim Res = Str.Substring(0, 1)
For i = 1 To Str.Length - 1
a = CChar(Str.Substring(i, 1))
If Res.IndexOf(a) = -1 Then
Res &= a
End If
Next
Return Res
End Function
Sub resh(ByVal filename1 As String, ByVal filename2 As String)
Dim lines = File.ReadAllLines(filename1)
Dim NewLines As New List(Of String)
For Each line In lines
Try
ListBox1.Items.Add(line)
Dim s2 = ch(line)
NewLines.Add(s2)
ListBox2.Items.Add(s2)
Catch ex As Exception
MsgBox(ex.Message)
End Try
Next
Dim Shortest = NewLines.OrderByDescending(Function(s) s.Length).Last()
File.WriteAllText(filename2, Shortest)
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim OpenPath = GetOpenPath()
Dim SavePath = GetSavePath()
If String.IsNullOrEmpty(OpenPath) OrElse String.IsNullOrEmpty(SavePath) Then
MessageBox.Show("You must provide a file. Try again.")
Return
End If
resh(OpenPath, SavePath)
End Sub

File synchronization Visual Studio 2015 error

I'm coming back to you because I still have a problem in my source code, I'll remind you that I'm trying to do an FTP synchronization from the following source that I copied
Video: https://www.youtube.com/watch?v=E5qSxrbrf9I
Error:
BC31143 La méthode 'Private Sub File_Downloaded(sender As Object, e As AsyncCompletedEventArgs)' n'a pas de signature compatible avec le délégué 'Delegate Sub DownloadProgressChangedEventHandler(sender As Object, e As DownloadProgressChangedEventArgs)'.
Erreur BC30311 Impossible de convertir une valeur de type 'FtpWebResponse' en 'FtpWebRequest'.
Erreur BC30456 'GetResponseStream' n'est pas un membre de 'FtpWebRequest'.
FTPManager.vb (Class)
Public Class FTPManager
Private Shared ConfigFile As String =
Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) & "\config.txt"
Public Shared Folder As String = "Client_Pokemonia"
Public Shared ServerRootPatch As String
Public Shared User As String
Public Shared PW As String
Public Shared Sub loadConfig()
If IO.File.Exists(ConfigFile) Then
Dim lines = IO.File.ReadAllLines(ConfigFile)
ServerRootPatch = lines(0)
User = lines(1)
PW = lines(2)
End If
End Sub
End Class
Form1.vb
Imports System.ComponentModel
Imports System.Net
Public Class Form1
Private LocalPath As String = "Downloadedfiles"
Private missingFiles As New List(Of String)
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
FTPManager.loadConfig()
createLocalFolderIfNotExistes()
btnRefresh.performClick()
End Sub
Private Sub createLocalFolderIfNotExistes()
If Not IO.Directory.Exists(LocalPath) Then IO.Directory.CreateDirectory(LocalPath)
End Sub
Private Sub getLocalFiles()
dgvLocal.Rows.clear
Dim files = IO.Directory.GetFiles(LocalPath)
If files.Count > 0 Then
For Each f In files
Me.dgvLocal.Rows.Add(f.Split("\c").Last())
Next
End If
End Sub
Private Sub getFTPFiles()
dgvFTP.Rows.Clear()
missingFiles.Clear()
Dim request = FtpWebRequest.Create(FTPManager.ServerRootPatch)
request.Method = WebRequestMethods.Ftp.ListDirectory
request.Credentials = New NetworkCredential(FTPManager.User, FTPManager.PW)
Dim response As FtpWebRequest = CType(request.GetResponse(), FtpWebResponse)
Using myReader As New IO.StreamReader(response.GetResponseStream())
Do Until Not myReader.EndOfStream
Dim file = myReader.ReadLine()
Me.dgvFTP.Rows.Add(file)
If Not IO.File.Exists(LocalPath & "\" & file) Then
dgvFTP.Rows(dgvFTP.Rows.Count - 1).defaultCellStyle.BackColor = Color.FromArgb(255, 192, 192)
missingFiles.Add(file)
Else : dgvFTP.Rows(dgvFTP.Rows.Count - 1).DefaultCellStyle.BackColor = Color.FromArgb(192, 255, 192)
End If
Loop
End Using
End Sub
Private Sub btnRefresh_Click(sender As Object, e As EventArgs) Handles btnRefresh.Click
' If Not btnRefresh Then
' btnRefresh.Enabled = False
' Await Task.Delay(2000)
' getLocalFiles()
' getFTPFiles()
' btnSync.Enabled = True
' Else : MessageBox.Show("please wait")
' End If
dgvFTP.ClearSelection()
dgvLocal.ClearSelection()
End Sub
Private Sub btnSync_Click(sender As Object, e As EventArgs) Handles btnSync.Click
If missingFiles.Count > 0 Then
Donwload_File(New Uri(FTPManager.ServerRootPatch & FTPManager.Folder & "/" & missingFiles(0)))
Else : MessageBox.Show("No files to downlaod")
End If
End Sub
Private Sub Donwload_File(URI As Uri)
Dim filename = URI.ToString().Split("/c").Last()
prgb.Value = 0
'lblFile.text = filename
Using wc As New WebClient
wc.Credentials = New NetworkCredential(FTPManager.User, FTPManager.PW)
AddHandler wc.DownloadProgressChanged, AddressOf File_DLProgressChanged
AddHandler wc.DownloadProgressChanged, AddressOf File_Downloaded
wc.DownloadFileAsync(URI, LocalPath & "\" & filename)
End Using
End Sub
Private Sub File_DLProgressChanged(sender As Object, e As DownloadProgressChangedEventArgs)
prgb.Value = e.ProgressPercentage
End Sub
Private Sub File_Downloaded(sender As Object, e As AsyncCompletedEventArgs)
Dim deletedFile = missingFiles(0)
missingFiles.RemoveAt(0)
If missingFiles.Count > 0 Then
Donwload_File(New Uri(FTPManager.ServerRootPatch & FTPManager.Folder & "/" & missingFiles(0)))
Else
btnRefresh.PerformClick()
MessageBox.Show("niquel")
End If
End Sub
End Class
The issue is here:
Dim response As FtpWebRequest = CType(request.GetResponse(), FtpWebResponse)
read what the error message is telling you and then read that line. You call GetResponse and cast the result as type FtpWebResponse, then you try to assign that top a variable of type FtpWebRequest. The error message is telling you that you can't convert an object of one type to the other, which would be required for that assignment to work.

Problems Reading File

Currently having issues reading data from a file, and assigning it to the text-boxes on my form. The code runs without throwing an error, but no data/values are passed to the text-boxes and they remain blank. Below is my code:
Imports System.IO
Public Class ReadingEmployeeData
' Declare filename
Dim FileName As String
Private Sub NextButton_Click(sender As Object, e As EventArgs) Handles NextButton.Click
' Constant for holding the number of fields
Const NumFields As Integer = 8
' Declare variables
Dim FileStream As StreamReader
Dim Count As Integer
Try
' Open file
FileStream = File.OpenText(FileName)
' Read the data
For Count = 1 To NumFields
FirstText.Text = FileStream.ReadLine()
MiddleText.Text = FileStream.ReadLine()
LastText.Text = FileStream.ReadLine()
NumberText.Text = FileStream.ReadLine()
DepartmentText.Text = FileStream.ReadLine()
PhoneText.Text = FileStream.ReadLine()
ExtText.Text = FileStream.ReadLine()
EmailText.Text = FileStream.ReadLine()
Next Count
Catch ex As Exception
MessageBox.Show("That file can not be opened.")
Finally
FileStream.Close()
End Try
End Sub
Private Sub ReadingEmployeeData_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Get the filename from user
FileName = InputBox("Please enter the name of the file")
End Sub
Private Sub ExitButton_Click(sender As Object, e As EventArgs) Handles ExitButton.Click
Me.Close()
End Sub
End Class
Try using Io.StreamReader, And there is no need to NumFields:
Imports System.IO
Public Class ReadingEmployeeData
' Declare filename
Dim FileName As String
Private Sub NextButton_Click(sender As Object, e As EventArgs) Handles NextButton.Click
' Declare variables
Dim FileStream As StreamReader
Dim Count As Integer
Try
' Open file
Using sr As New Io.StreamReader(FileName)
' Read the data
FirstText.Text = sr.ReadLine()
MiddleText.Text = sr.ReadLine()
LastText.Text = sr.ReadLine()
NumberText.Text = sr.ReadLine()
DepartmentText.Text = sr.ReadLine()
PhoneText.Text = sr.ReadLine()
ExtText.Text = sr.ReadLine()
EmailText.Text = sr.ReadLine()
sr.Close()
End Using
Catch ex As Exception
MessageBox.Show("That file can not be opened.")
End Try
End Sub
Private Sub ReadingEmployeeData_Load(sender As Object, e As EventArgs) Handles MyBase.Load
' Get the filename from user
FileName = InputBox("Please enter the name of the file")
End Sub
Private Sub ExitButton_Click(sender As Object, e As EventArgs) Handles ExitButton.Click
Me.Close()
End Sub
End Class

Save clicks to file

I got asked a couple of days ago how to save number of clicks you have done to each button in a program to a small file, to keep track of what is most used. Since it was ages ago i dabbled with visual basic i said i would raise the question here, so here goes.
There are 5 buttons labels Button1-Button5. When a button is clicked it should look for the correct value in a file.txt and add +1 to the value. The file is structured like this.
Button1 = 0
Button2 = 0
Button3 = 0
Button4 = 0
Button5 = 0
So when button1 is clicked it should open file.txt, look for the line containing Button1 and add +1 to the value and close the file.
I have tried looking for some kind of tutorial on this but have not found it so i'm asking the collective of brains here on Stackoverflow for some guidance.
Thanks in advance.
delete file first
new ver ..
Imports System.IO.File
Imports System.IO.Path
Imports System.IO
Imports System.Text
Public Class Form1
Dim line() As String
Dim strbild As StringBuilder
Dim arr() As String
Dim i As Integer
Dim pathAndFile As String
Dim addLine As System.IO.StreamWriter
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim fileName As String = "myfile.txt"
Dim appPath As String = My.Application.Info.DirectoryPath
pathAndFile = Path.Combine(appPath, fileName)
If System.IO.File.Exists(pathAndFile) Then
'line = File.ReadAllLines(pathAndFile)
Else
Dim addLineToFile = System.IO.File.CreateText(pathAndFile) 'Create an empty txt file
Dim countButtons As Integer = 5 'add lines with your desired number of buttons
For i = 1 To countButtons
addLineToFile.Write("Button" & i & " = 0" & vbNewLine)
Next
addLineToFile.Dispose() ' and close file
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
writeToFile(1)
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
writeToFile(2)
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
writeToFile(3)
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
writeToFile(4)
End Sub
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
writeToFile(5)
End Sub
Public Sub writeToFile(buttonId As Integer)
Dim tmpButton As String = "Button" & buttonId
strbild = New StringBuilder
line = File.ReadAllLines(pathAndFile)
Dim f As Integer = 0
For Each lineToedit As String In line
If InStr(1, lineToedit, tmpButton) > 0 Then
Dim lineSplited = lineToedit.Split
Dim cnt As Integer = lineSplited.Count
Dim newVal = addCount(CInt(lineSplited.Last()))
lineSplited(cnt - 1) = newVal
lineToedit = String.Join(" ", lineSplited)
line(f) = lineToedit
End If
f = f + 1
Next
strbild = New StringBuilder
'putting together all the reversed word
For j = 0 To line.GetUpperBound(0)
strbild.Append(line(j))
strbild.Append(vbNewLine)
Next
' writing to original file
File.WriteAllText(pathAndFile, strbild.ToString())
Me.Refresh()
End Sub
' Reverse Function
Public Function ReverseString(ByRef strToReverse As String) As String
Dim result As String = ""
For i As Integer = 0 To strToReverse.Length - 1
result += strToReverse(strToReverse.Length - 1 - i)
Next
Return result
End Function
Public Function addCount(ByVal arr As Integer) As Integer
Return arr + 1
End Function
End Class
Output in myfile.txt
Button1 = 9
Button2 = 2
Button3 = 4
Button4 = 0
Button5 = 20
Create a vb winform Application
Drag on your form 5 buttons (Button1, Button2, ... etc)
copy that :
Imports System.IO.File
Imports System.IO.Path
Imports System.IO
Imports System.Text
Public Class Form1
Dim line() As String
Dim strbild As StringBuilder
Dim arr() As String
Dim i As Integer
Dim pathAndFile As String
Dim addLine As System.IO.StreamWriter
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim fileName As String = "myfile.txt"
Dim appPath As String = My.Application.Info.DirectoryPath
pathAndFile = Path.Combine(appPath, fileName)
If System.IO.File.Exists(pathAndFile) Then
line = File.ReadAllLines(pathAndFile)
Else
Dim addLineToFile = System.IO.File.CreateText(pathAndFile) 'Create an empty txt file
Dim countButtons As Integer = 5 'add lines with your desired number of buttons
For i = 1 To countButtons
addLineToFile.Write("Button" & i & " = 0" & vbNewLine)
Next
addLineToFile.Dispose() ' and close file
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
writeToFile(1)
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
writeToFile(2)
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
writeToFile(3)
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
writeToFile(4)
End Sub
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
writeToFile(5)
End Sub
Public Sub writeToFile(buttonId As Integer)
Dim tmpButton As String = "Button" & buttonId
strbild = New StringBuilder
line = File.ReadAllLines(pathAndFile)
i = 0
For Each lineToedit As String In line
If lineToedit.Contains(tmpButton) Then
Dim lineSplited = lineToedit.Split
Dim newVal = addCount(CInt(lineSplited.Last()))
'lineToedit.Replace(lineSplited.Last, newVal)
lineToedit = lineToedit.Replace(lineToedit.Last, newVal)
line(i) = lineToedit
End If
i = i + 1
Next
strbild = New StringBuilder
'putting together all the reversed word
For j = 0 To line.GetUpperBound(0)
strbild.Append(line(j))
strbild.Append(vbNewLine)
Next
' writing to original file
File.WriteAllText(pathAndFile, strbild.ToString())
End Sub
' Reverse Function
Public Function ReverseString(ByRef strToReverse As String) As String
Dim result As String = ""
For i As Integer = 0 To strToReverse.Length - 1
result += strToReverse(strToReverse.Length - 1 - i)
Next
Return result
End Function
Public Function addCount(ByVal arr As Integer) As Integer
Return arr + 1
End Function
End Class
Have fun ! :)CristiC777
try this on vs2013
change If confition
line = File.ReadAllLines(pathAndFile)
i = 0
For Each lineToedit As String In line
If InStr(1, lineToedit, tmpButton) > 0 Then
'If lineToedit.Contains(tmpButton) = True Then
Dim lineSplited = lineToedit.Split
Dim newVal = addCount(CInt(lineSplited.Last()))
lineToedit = lineToedit.Replace(lineToedit.Last, newVal)
line(i) = lineToedit
End If
i = i + 1
Next

Path from URL not from C:/ Drive

I found one code which auto-change proxies from own text file located in computer.
Now I would like to rather this get path from my own URL where I store my private list of proxies, so what I have to change in the code please? and could also someone explain why? thank you.
Imports System
Imports System.Runtime.InteropServices
Imports System.IO
Imports Microsoft.VisualBasic
Imports System.Timers
Public Class Form1
Dim FILE_NAME As String = "C:\Users\name\Documents\proxylist.txt"
Dim label As String
Public proxy(2000) As String
Public index As Integer = 0
Public max_proxys As Integer = 0
Dim a As String
Dim start_check As Integer = 0
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If (start_check > 0) Then
index = 0
Do While index <> max_proxys
proxy(index) = ""
index = index + 1
Loop
If TextBox3.Text = "" Then
FILE_NAME = "C:\Users\name\Documents\proxylist.txt"
End If
End If
If TextBox3.Text <> "" Then
FILE_NAME = TextBox3.Text
End If
Try
Dim reader As StreamReader = My.Computer.FileSystem.OpenTextFileReader(FILE_NAME)
index = 0
Do While reader.Peek <> -1
a = reader.ReadLine
proxy(index) = a.ToString
index = index + 1
Loop
max_proxys = index
reader.Close()
Catch ex As Exception
MessageBox.Show("File Not Found")
Timer1.Stop()
End Try
label = "true"
index = 0
TextBox1.Text = proxy(0)
If TextBox2.Text = "" Then
Timer1.Interval = 1000 'ms
Else
Try
Dim a As Integer = Convert.ToDecimal(TextBox2.Text)
Timer1.Interval = a * 1000 'ms
Catch ex As Exception
MessageBox.Show(ex.Message & "Please Enter Valid Time in Seconds ")
If Timer1.Enabled Then
Timer1.Stop()
End If
End Try
End If
start_check = 1
Timer1.Start()
End Sub
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
label = "false"
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim clsProxy As New IEProxy
clsProxy.DisableProxy()
End Sub
Private Sub Timer1_Tick_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Timer1.Stop()
TextBox1.Text = proxy(index)
index = index + 1
Dim clsProxy As New IEProxy
If clsProxy.SetProxy(TextBox1.Text) Then
MessageBox.Show("Proxy successfully enabled.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
MessageBox.Show("Error enabling proxy.", "Failed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
If index >= max_proxys Then
index = 0
End If
If label.Equals("false") Then
Timer1.Stop()
End If
End Sub
End Class
Public Class IEProxy
Public Enum Options
INTERNET_PER_CONN_FLAGS = 1
INTERNET_PER_CONN_PROXY_SERVER = 2
INTERNET_PER_CONN_PROXY_BYPASS = 3
INTERNET_PER_CONN_AUTOCONFIG_URL = 4
INTERNET_PER_CONN_AUTODISCOVERY_FLAGS = 5
INTERNET_OPTION_REFRESH = 37
INTERNET_OPTION_PER_CONNECTION_OPTION = 75
INTERNET_OPTION_SETTINGS_CHANGED = 39
PROXY_TYPE_PROXY = &H2
PROXY_TYPE_DIRECT = &H1
End Enum
<StructLayout(LayoutKind.Sequential)> _
Private Class FILETIME
Public dwLowDateTime As Integer
Public dwHighDateTime As Integer
End Class
<StructLayout(LayoutKind.Explicit, Size:=12)> _
Private Structure INTERNET_PER_CONN_OPTION
<FieldOffset(0)> Dim dwOption As Integer
<FieldOffset(4)> Dim dwValue As Integer
<FieldOffset(4)> Dim pszValue As IntPtr
<FieldOffset(4)> Dim ftValue As IntPtr
Public Function GetBytes() As Byte()
Dim b(12) As Byte
BitConverter.GetBytes(dwOption).CopyTo(b, 0)
Select Case dwOption
Case Options.INTERNET_PER_CONN_FLAGS
BitConverter.GetBytes(dwValue).CopyTo(b, 4)
Case Options.INTERNET_PER_CONN_PROXY_BYPASS
BitConverter.GetBytes(pszValue.ToInt32()).CopyTo(b, 4)
Case Options.INTERNET_PER_CONN_PROXY_SERVER
BitConverter.GetBytes(pszValue.ToInt32()).CopyTo(b, 4)
End Select
Return b
End Function
End Structure
<StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Auto)> _
Private Class INTERNET_PER_CONN_OPTION_LIST
Public dwSize As Integer
Public pszConnection As String
Public dwOptionCount As Integer
Public dwOptionError As Integer
Public pOptions As IntPtr
End Class
<StructLayout(LayoutKind.Sequential)> _
Private Class INTERNET_PROXY_INFO
Public dwAccessType As Integer
Public lpszProxy As IntPtr
Public lpszProxyBypass As IntPtr
End Class
Private Const ERROR_INSUFFICIENT_BUFFER = 122
Private Const INTERNET_OPTION_PROXY = 38
Private Const INTERNET_OPEN_TYPE_DIRECT = 1
<DllImport("wininet.dll")> _
Private Shared Function InternetSetOption(ByVal hInternet As IntPtr, _
ByVal dwOption As Integer, _
ByVal lpBuffer As INTERNET_PER_CONN_OPTION_LIST, _
ByVal dwBufferLength As Integer) As Boolean
End Function
<DllImport("kernel32.dll")> _
Private Shared Function GetLastError() As Integer
End Function
Public Function SetProxy(ByVal proxy_full_addr As String) As Boolean
Dim bReturn As Boolean
Dim list As New INTERNET_PER_CONN_OPTION_LIST
Dim dwBufSize As Integer = Marshal.SizeOf(list)
Dim opts(3) As INTERNET_PER_CONN_OPTION
Dim opt_size As Integer = Marshal.SizeOf(opts(0))
list.dwSize = dwBufSize
list.pszConnection = ControlChars.NullChar
list.dwOptionCount = 3
'set flags
opts(0).dwOption = Options.INTERNET_PER_CONN_FLAGS
opts(0).dwValue = Options.PROXY_TYPE_DIRECT Or Options.PROXY_TYPE_PROXY
'set proxyname
opts(1).dwOption = Options.INTERNET_PER_CONN_PROXY_SERVER
opts(1).pszValue = Marshal.StringToHGlobalAnsi(proxy_full_addr)
'set override
opts(2).dwOption = Options.INTERNET_PER_CONN_PROXY_BYPASS
opts(2).pszValue = Marshal.StringToHGlobalAnsi("local")
Dim b(3 * opt_size) As Byte
opts(0).GetBytes().CopyTo(b, 0)
opts(1).GetBytes().CopyTo(b, opt_size)
opts(2).GetBytes().CopyTo(b, 2 * opt_size)
Dim ptr As IntPtr = Marshal.AllocCoTaskMem(3 * opt_size)
Marshal.Copy(b, 0, ptr, 3 * opt_size)
list.pOptions = ptr
'Set the options on the connection
bReturn = InternetSetOption(IntPtr.Zero, Options.INTERNET_OPTION_PER_CONNECTION_OPTION, list, dwBufSize)
If Not bReturn Then
Debug.WriteLine(GetLastError)
End If
'Notify existing Internet Explorer instances that the settings have changed
bReturn = InternetSetOption(IntPtr.Zero, Options.INTERNET_OPTION_SETTINGS_CHANGED, Nothing, 0)
If Not bReturn Then
Debug.WriteLine(GetLastError)
End If
'Flush the current IE proxy setting
bReturn = InternetSetOption(IntPtr.Zero, Options.INTERNET_OPTION_REFRESH, Nothing, 0)
If Not bReturn Then
Debug.WriteLine(GetLastError)
End If
Marshal.FreeHGlobal(opts(1).pszValue)
Marshal.FreeHGlobal(opts(2).pszValue)
Marshal.FreeCoTaskMem(ptr)
Return bReturn
End Function
Public Function DisableProxy() As Boolean
Dim bReturn As Boolean
Dim list As New INTERNET_PER_CONN_OPTION_LIST
Dim dwBufSize As Integer = Marshal.SizeOf(list)
Dim opts(0) As INTERNET_PER_CONN_OPTION
Dim opt_size As Integer = Marshal.SizeOf(opts(0))
list.dwSize = dwBufSize
list.pszConnection = ControlChars.NullChar
list.dwOptionCount = 1
opts(0).dwOption = Options.INTERNET_PER_CONN_FLAGS
opts(0).dwValue = Options.PROXY_TYPE_DIRECT
Dim b(opt_size) As Byte
opts(0).GetBytes().CopyTo(b, 0)
Dim ptr As IntPtr = Marshal.AllocCoTaskMem(opt_size)
Marshal.Copy(b, 0, ptr, opt_size)
list.pOptions = ptr
'Set the options on the connection
bReturn = InternetSetOption(IntPtr.Zero, Options.INTERNET_OPTION_PER_CONNECTION_OPTION, list, dwBufSize)
If Not bReturn Then
Debug.WriteLine(GetLastError)
End If
'Notify existing Internet Explorer instances that the settings have changed
bReturn = InternetSetOption(IntPtr.Zero, Options.INTERNET_OPTION_SETTINGS_CHANGED, Nothing, 0)
If Not bReturn Then
Debug.WriteLine(GetLastError)
End If
'Flush the current IE proxy setting
bReturn = InternetSetOption(IntPtr.Zero, Options.INTERNET_OPTION_REFRESH, Nothing, 0)
If Not bReturn Then
Debug.WriteLine(GetLastError)
End If
Marshal.FreeCoTaskMem(ptr)
Return bReturn
End Function
End Class
Maybe just download your url to the FILE_NAME location in your form's load event. Be warned that if there is a file at FILE_NAME, this sub I provide you will overwrite it.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim YourURL As String = "http://www.yoururl.com/filename.ext"
Using w As New System.Net.WebClient
w.DownloadFile(YourURL, FILE_NAME)
End Using
End Sub