System.I.O the process cannot access the file because it is being used by another process - vb.net

I'm designing a program that calculates the average of scores. the program works great except when I try to add a name and a number from textbox into the textfile it returns an error. I believe that I have closed the file every time it has been used. my code is:
Public Class Form4
Public Function GetNumberOfLines(ByVal file_path As String) As Integer
Using sr As New StreamReader("C:\file.txt")
Dim NumberOfLines As Integer
Do While sr.Peek >= 0 'a pre test loop to read lines
sr.ReadLine()
NumberOfLines += 1
Loop
Return NumberOfLines
sr.Close() 'closes file after it is read
sr.Dispose()
End Using
End Function
Private Sub Form4_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Hide()
End Sub
Private Sub Button9_Click(sender As Object, e As EventArgs) Handles Button9.Click
Dim FILE_NAME As String = "C:\file.txt"
If System.IO.File.Exists(FILE_NAME) = True Then
Dim objWriter As New System.IO.StreamWriter(FILE_NAME)
objWriter.Close()
objWriter.Write(TextBox5.Text)
MsgBox("Text written to file")
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Using sr As New System.IO.StreamReader("C:\file.txt")
Dim LofInt As New List(Of Integer)
While sr.Peek <> -1
Dim line As String = sr.ReadLine
Dim intValue As String = String.Empty
For Each c As Char In line
If IsNumeric(c) Then
intValue += c
End If
Next
LofInt.Add(intValue)
End While
sr.Close()
sr.Dispose()
LofInt.Sort()
For Each i In LofInt
Scores.Items.Add(i)
Next
Dim sum As Decimal
For Each decAdded As Decimal In Me.Scores.Items
sum += Double.Parse(decAdded)
Next
TextBox4.Text = sum
sr.Close()
sr.Dispose()
End Using
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
TextBox1.Text = My.Computer.FileSystem.ReadAllText("C:\file.txt")
TextBox2.Text = GetNumberOfLines("C:\file.txt")
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim sum As Decimal
Dim avg As Decimal
For Each decAdded As Decimal In Me.Scores.Items
sum += Double.Parse(decAdded)
Next
avg = sum / (GetNumberOfLines("C:\file.txt"))
TextBox3.Text = avg
End Sub
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Close()
End Sub
Private Sub TextBox5_TextChanged(sender As Object, e As EventArgs)
End Sub
Private Sub Button8_Click(sender As Object, e As EventArgs) Handles Button8.Click
TextBox1.Clear()
TextBox2.Clear()
Scores.Items.Clear()
TextBox4.Clear()
TextBox1.Text = My.Computer.FileSystem.ReadAllText("C:\file.txt")
TextBox2.Text = GetNumberOfLines("C:\file.txt")
Using sr As New System.IO.StreamReader("C:\file.txt")
Dim LofInt As New List(Of Integer)
While sr.Peek <> -1
Dim line As String = sr.ReadLine
Dim intValue As String = String.Empty
For Each c As Char In line
If IsNumeric(c) Then
intValue += c
End If
Next
LofInt.Add(intValue)
End While
LofInt.Sort()
For Each i In LofInt
Scores.Items.Add(i)
Next
Dim sum As Decimal
For Each decAdded As Decimal In Me.Scores.Items
sum += Double.Parse(decAdded)
Next
TextBox4.Text = sum
sr.Close()
sr.Dispose()
End Using
End Sub
Dim objWriter As New System.IO.StreamWriter(FILE_NAME) is where the error occurs

Related

How can I close the PrintPreviewDialog once the printing is complete?

As a new programmer in VB, I struggled to get my print routine working. Searching through a number of sources I developed the hybrid below which is working to print a simple .txt file. My question sounds like a simple one but I've learned nothing is simple in printing. How do I get the PrintPreviewDialog to close once the printing is complete?
Private Sub BtnPrint_Click(sender As Object, e As EventArgs) Handles BtnPrint.Click
Try
PrintPreviewDialog1.Document = PrintDocument1
PageSetupDialog1.PageSettings =
PrintDocument1.DefaultPageSettings
If PageSetupDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
PrintDocument1.DefaultPageSettings =
PageSetupDialog1.PageSettings
PrintPreviewDialog1.Size = New System.Drawing.Size(500, 600)
PrintPreviewDialog1.ShowDialog()
End If
Catch ex As Exception
MessageBox.Show("Printing Operation Failed" & vbCrLf &
ex.Message)
End Try
End Sub
Private Sub PrintDocument1_PrintPage(sender As Object, e As PrintPageEventArgs) Handles PrintDocument1.PrintPage
Static MyNewAcctFile As String = IO.File.ReadAllText(strErrorFile)
Dim printFont As New Font("Arial", 14, FontStyle.Regular)
Dim charsFitted As Integer
Dim linesFilled As Integer
e.Graphics.MeasureString(MyNewAcctFile, printFont, New SizeF(e.MarginBounds.Width, e.MarginBounds.Height), Drawing.StringFormat.GenericTypographic, charsFitted, linesFilled)
e.Graphics.DrawString(MyNewAcctFile, printFont, Brushes.Black, e.MarginBounds, Drawing.StringFormat.GenericTypographic)
MyNewAcctFile = MyNewAcctFile.Substring(charsFitted)
If MyNewAcctFile <> "" Then
e.HasMorePages = True
Else
e.HasMorePages = False
MyNewAcctFile = IO.File.ReadAllText(strErrorFile)
End If
End Sub
I would expect to see something more like:
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
PrintPreviewDialog1.Document = PrintDocument1
PrintPreviewDialog1.ShowDialog()
End Sub
Private FileName As String
Private txtFileContents As String
Private Sub PrintDocument1_BeginPrint(sender As Object, e As PrintEventArgs) Handles PrintDocument1.BeginPrint
FileName = "C:\Users\mikes\Documents\SomeFile.txt"
txtFileContents = IO.File.ReadAllText(FileName)
End Sub
Private Sub PrintDocument1_PrintPage(sender As Object, e As PrintPageEventArgs) Handles PrintDocument1.PrintPage
If txtFileContents.Length > 0 Then
Using printFont As New Font("Arial", 14, FontStyle.Regular)
Dim charsFitted As Integer
Dim linesFilled As Integer
e.Graphics.MeasureString(txtFileContents, printFont, New SizeF(e.MarginBounds.Width, e.MarginBounds.Height), Drawing.StringFormat.GenericTypographic, charsFitted, linesFilled)
e.Graphics.DrawString(txtFileContents, printFont, Brushes.Black, e.MarginBounds, Drawing.StringFormat.GenericTypographic)
txtFileContents = txtFileContents.Substring(charsFitted)
e.HasMorePages = (txtFileContents.Length > 0)
End Using
End If
End Sub
Private Sub PrintDocument1_EndPrint(sender As Object, e As PrintEventArgs) Handles PrintDocument1.EndPrint
If Not PrintDocument1.PrintController.IsPreview Then
PrintPreviewDialog1.Close()
End If
End Sub
End Class

Saving and reading files on Visual basic

Hi I'm creating a "Toilet paper tracker" on visual basic and I'm struggling with saving and reading files, I know I am missing stuff. The user should be able to login and input a threshold and when reached a warning will pop up saying "buy more toilet paper" (i haven't coded this yet) and the user can add to create a total and subtract from it too. The user should also be able to save the total to a file and I want the program to be able to read the file and change the total if the user wants to add or subtract again. It would be greatly appreciated if you pointed me in the right direction, I'm only young so it's relatively simple. Here is my program :)
Imports System.IO
Public Class frmTPT
Private Sub TPT_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Call loadchangetotal()
End Sub
Sub loadchangetotal()
cboChange.Items.Add("Add to Total")
cboChange.Items.Add("Subtract from Total")
End Sub
Private Sub cboVenue_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboChange.SelectedIndexChanged
If cboChange.Text = "Add to Total" Then
Dim frmChangeACopy As New frmChangeA
frmChangeACopy.Show()
Me.Hide()
ElseIf cboChange.Text = "Subtract from Total" Then
Dim frmChangeSCopy As New frmChangeS
frmChangeSCopy.Show()
Me.Hide()
End If
End Sub
Private Sub btnReturn_Click(sender As Object, e As EventArgs)
Dim frmLoginCopy As New frmLogin
frmLoginCopy.Show()
Me.Hide()
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
txtThreshold.Text = ""
cboChange.Text = ""
txtTotal.Text = ""
End Sub
Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click
End
End Sub
Private Sub LogoutToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles LogoutToolStripMenuItem.Click
Dim frmLoginCopy As New frmLogin
frmLoginCopy.Show()
Me.Hide()
End Sub
Private Sub btnReadTotal_Click(sender As Object, e As EventArgs) Handles btnReadTotal.Click
Dim FileReader As StreamReader
Dim result As DialogResult
result = OpenFileDialog1.ShowDialog
If result = DialogResult.OK Then
FileReader = New StreamReader(OpenFileDialog1.Filename)
txtFileContent.Text = FileReader.ReadToEnd() 'i want to be able to read a
'previously saved total so that
FileReader.Close() 'it can be used to find the new total
'after it has been added to
End If 'or subtratced
End Sub
Private Sub SaveToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles SaveToolStripMenuItem.Click
Call SaveFile()
End Sub
Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click
Dim A, S, NewTotal As Integer
A = Val(frmChangeA.txtAdd.Text)
S = Val(frmChangeS.txtSubtract.Text)
NewTotal = A - S 'I want to be able to load a previously saved total if one exists and add and
'subtract from it
End Sub
End Class
Sub SaveFile()
Dim FileWriter As StreamWriter
Dim results As DialogResult
results = SaveFileDialog1.ShowDialog
If results = DialogResult.OK Then
FileWriter = New StreamWriter(SaveFileDialog1.FileName, False)
FileWriter.Write(txtFileContent.Text) ' is txtFileContent supposed to be
' the name of my textbox?
FileWriter.Close()
End If
End Sub
Design
You didn't mention if you were using .Net Core or 4.x. If the later, you can sometimes use the Insert Snippet functionality to learn how to do common tasks. For example in this case you could right click in the code editor and select Insert Snippet then Fundamentals then File System and finally Write text to a file. This will result in the following VB code:
My.Computer.FileSystem.WriteAllText("C:\Test.txt", "Text", True)
Unfortunately, this option doesn't work with .Net core since the My namespace wasn't ported to core.
The key point of this problem lies in reading and writing data from text. It is a clear idea to write two methods to achieve read and write.
You can refer to the following code. The two methods in the following example are WriteTotal(), ReadTotal().
Design:
Public Class Form1
Dim Oldtotal As Integer
Dim Newtotal As Integer
Private Sub btnLoadTotal_Click(sender As Object, e As EventArgs) Handles btnLoadTotal.Click
WriteTotal()
ReadTotal()
End Sub
Private Sub btnUpdateTotal_Click(sender As Object, e As EventArgs) Handles btnUpdateTotal.Click
cboChange.Text = Nothing
WriteTotal()
ReadTotal()
MsgBox("Inventory updated")
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
cboChange.SelectedIndex = 0
ReadTotal()
End Sub
Sub WriteTotal()
Using swriter As IO.StreamWriter = New IO.StreamWriter("D:/paperstore.txt", False, System.Text.Encoding.UTF8)
If cboChange.Text = "Add to Total" Then
Newtotal = Oldtotal + CType(txtThreshold.Text, Integer)
swriter.WriteLine(Newtotal)
ElseIf cboChange.Text = "Subtract from Total" Then
If CType(txtThreshold.Text, Integer) > Oldtotal Then
swriter.WriteLine(Oldtotal)
MsgBox("buy more toilet paper")
Else
Newtotal = Oldtotal - CType(txtThreshold.Text, Integer)
swriter.WriteLine(Newtotal)
End If
Else
swriter.WriteLine(txtTotal.Text)
End If
End Using
End Sub
Sub ReadTotal()
Using sreader As IO.StreamReader = New IO.StreamReader("D:/paperstore.txt", System.Text.Encoding.UTF8)
Try
Oldtotal = sreader.ReadLine()
txtTotal.Text = Oldtotal
Catch ex As Exception
MsgBox(ex.Message)
End
End Try
End Using
End Sub
End Class

How I can change the text of a single label from a string array vb.net?

so I want to display a string array in a single label that change the contents with a period of time ,
I ve tried every thing the timer, the background worker every thing , the problem when I use a loop inset a timer the interval in the start should be so long if the array items was so many so I tried the background worker but it not works
this is the code :
Dim array() As String = {"so", "nb", "de", "rty", "dcds"}
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Control.CheckForIllegalCrossThreadCalls = False
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)
Dim delay As Integer = 2000
Dim interval As Integer = 100
Dim elapsed As Integer = 0
Dim pos As Integer = array.Length
While Not worker.CancellationPending
If (elapsed >= delay) Then
worker.ReportProgress(pos)
' change label text in the Progress event handler
pos = (pos + 1)
elapsed = 0
If (pos = array.Length) Then
Exit While
End If
End If
Thread.Sleep(interval)
End While
End Sub
Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
Dim j As Integer
For j = 0 To array.Length
Label1.Text = array(j)
Next
End Sub
Your for loop is overwriting the .Text property of the lable on each iteration. You will also get an Index Out of Range exception because the indexes of an array are zero based. The highest index will be 1 less than the .Length.
Private arStr() As String = {"so", "nb", "de", "rty", "dcds"}
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim LabelText = String.Join(Environment.NewLine, arStr)
Label1.Text = LabelText
End Sub
EDIT
Private arStr() As String = {"so", "nb", "de", "rty", "dcds"}
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Static index As Integer
If index < arStr.Length Then
Label1.Text &= arStr(index) & Environment.NewLine
index += 1
End If
End Sub
With asynchronous approach you can display array values one after another without BackgroundWorker and explicitly created Timer.
Private _values As New String() From {"so", "nb", "de", "rty", "dcds"}
Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
For Each value In _values
await Task.Delay(2000)
Next
End Sub
With asynchronous approach you can prevent button click before all values are displayed in the simple way as you would do in synchronous code.
Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim button = DirectCast(sender, Button);
button.Enabled = False
For Each value In _values
await Task.Delay(2000)
Next
button.Enabled = True
End Sub

Add items to listview after cleared

I am adding all the textboxes and labels to display in the listview. When I click the clear button everything on my form clears as it should, but when I then want to add more items to the listview, nothing displays in the listview, and my header information is also cleared. Can someone please assist?
Public Class Form2
Dim decTotalDue As Decimal
Dim intTotalItems As Integer
Private Sub TextBox2_TextChanged(sender As Object, e As EventArgs) Handles txtUnitPrice.TextChanged
End Sub
Private Sub btnAddItem_Click(sender As Object, e As EventArgs) Handles btnAddItem.Click
Dim decUnitPrice As Decimal
Dim intQuantity As Integer
Dim decTotal As Decimal
Dim decTotalPayable As Decimal
Dim item As New ListViewItem
Decimal.TryParse(txtUnitPrice.Text, decUnitPrice)
Integer.TryParse(txtQuantity.Text, intQuantity)
decTotal = decUnitPrice * intQuantity
lblTotal.Text = decTotal.ToString("C2")
decTotalDue = decTotal + decTotalDue
lblTotalDue.Text = decTotalDue.ToString("C2")
intTotalItems = intQuantity + intTotalItems
lblTotalItems.Text = intTotalItems.ToString
decTotalPayable = decTotalDue
lblTotalPayable.Text = decTotalPayable.ToString("C2")
lblTotalPayable.Hide()
lblTotalItems.Hide()
item = ListView1.Items.Add(cboItemName.Text)
item.SubItems.Add(txtUnitPrice.Text)
item.SubItems.Add(txtQuantity.Text)
item.SubItems.Add(lblTotal.Text)
ListView1.ForeColor = Color.White
txtUnitPrice.Text = decUnitPrice.ToString("C2")
End Sub
Private Sub btnPurchase_Click(sender As Object, e As EventArgs) Handles btnPurchase.Click
lblTotalItems.Show()
lblTotalPayable.Show()
cboItemName.Text = String.Empty
txtUnitPrice.Clear()
txtQuantity.Clear()
lblTotal.Text = ""
lblTotalDue.Text = ""
ListView1.Clear()
End Sub
Private Sub btnCalculateChange_Click(sender As Object, e As EventArgs) Handles btnCalculateChange.Click
Dim decCashTenderted As Decimal
Dim decChange As Decimal
Decimal.TryParse(txtCashTendered.Text, decCashTenderted)
txtCashTendered.Text = decCashTenderted.ToString("C2")
decChange = decCashTenderted - decTotalDue
lblChange.Text = decChange.ToString("C2")
If decCashTenderted < decTotalDue Then
MessageBox.Show("Cash Tendered is less than Total Due", "Invalid", MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning)
End If
End Sub
Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
Me.Close()
End Sub
Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
cboItemName.Text = String.Empty
txtCashTendered.Clear()
txtUnitPrice.Clear()
txtQuantity.Clear()
lblTotalDue.Text = ""
lblTotalItems.Text = ""
lblTotalPayable.Text = ""
lblChange.Text = ""
ListView1.Clear()
End Sub
Private Sub ListView1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListView1.SelectedIndexChanged
End Sub
End Class
MSDN on the behaviour of the Clear function is:
You can use this method to remove all items and columns from the ListView control without having to call the individual Clear methods from the ListView.ColumnHeaderCollection and ListView.ListViewItemCollection classes.
From what you describe you want, you should be doing is calling:
ListView1.Items.Clear()
This will remove just the items that are displayed and not remove the column definitions.

How to determine if a value of a key exist in my settings vb.net

i have start to develop a new application to generate md5 hashes from strings and the it save automatic to my.settings.md5_hashes
and now i need to check if a certain value all ready exist in my settings md5_hashes. i have find some examples but it give me all ways a error on it
the error
Error 1 Value of type 'System.Collections.Specialized.StringCollection' cannot be converted to 'String'.
how can i check if a value its all ready exist on my settings?
This is my code
Public Class Form3
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If My.Settings.md5_hashes = (TextBox1.Text) Then
End If
If Not My.Settings.md5_hashes = (TextBox1.Text) Then
Me.Show()
End If
End Sub
End Class
This is the code to generate the hashes and save it to my.settings.md5_hashes
Imports System.Text
Imports System.Security.Cryptography
Imports System
Imports System.Collections
Imports System.Collections.Specialized
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
My.Settings.md5_hashes.Clear()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim md5 As MD5 = System.Security.Cryptography.MD5.Create()
Dim inputBytes As Byte() = System.Text.Encoding.ASCII.GetBytes(TextBox1.Text)
Dim hash As Byte() = md5.ComputeHash(inputBytes)
Dim sb As New StringBuilder()
For i As Integer = 0 To hash.Length - 1
sb.Append(hash(i).ToString("x2"))
Next
TextBox2.Text = sb.ToString
ListBox1.Items.Add(TextBox1.Text + "<--->" + TextBox2.Text)
My.Settings.md5_hashes.Add(TextBox1.Text + "<--->" + TextBox2.Text)
My.Settings.Save()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
For Each item In My.Settings.md5_hashes
ListBox1.Items.Add(item)
Next
Timer1.Start()
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
TextBox1.Text = ""
TextBox2.Text = ""
ListBox1.Items.Clear()
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Form2.Show()
End Sub
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
Dim W As IO.StreamWriter
Dim i As Integer
W = New IO.StreamWriter("C:\MD5.txt", True)
For i = 0 To ListBox1.Items.Count - 1
W.WriteLine(ListBox1.Items.Item(i))
Next
W.Close()
MsgBox("You File Is Save You Can Locate It At C:\MD5.txt")
End Sub
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
Form3.Show()
End Sub
End Class
well i have just change some part of the code
this is my new code
Imports System.Text
Imports System.Security.Cryptography
Imports System
Imports System.Collections
Imports System.Collections.Specialized
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'My.Settings.md5_hashes.Clear()
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim md5 As MD5 = System.Security.Cryptography.MD5.Create()
Dim inputBytes As Byte() = System.Text.Encoding.ASCII.GetBytes(TextBox1.Text)
Dim hash As Byte() = md5.ComputeHash(inputBytes)
Dim sb As New StringBuilder()
For i As Integer = 0 To hash.Length - 1
sb.Append(hash(i).ToString("x2"))
Next
TextBox2.Text = sb.ToString
ListBox1.Items.Add(TextBox1.Text)
ListBox1.Items.Add(TextBox2.Text)
My.Settings.md5_hashes.Add(TextBox1.Text)
My.Settings.md5_hashes.Add(TextBox2.Text)
My.Settings.md5_hashes.Add("<--->")
My.Settings.Save()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
For Each item In My.Settings.md5_hashes
ListBox1.Items.Add(item)
Next
Timer1.Start()
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
End Sub
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
TextBox1.Text = ""
TextBox2.Text = ""
ListBox1.Items.Clear()
End Sub
Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
Form2.Show()
End Sub
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
Dim W As IO.StreamWriter
Dim i As Integer
W = New IO.StreamWriter("C:\MD5.txt", True)
For i = 0 To ListBox1.Items.Count - 1
W.WriteLine(ListBox1.Items.Item(i))
Next
W.Close()
MsgBox("You File Is Save You Can Locate It At C:\MD5.txt")
End Sub
Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
Form3.Show()
End Sub
End Class
well now its return true but how can i get the value to show on a msgbox the results?
well i solved my self the way to get results of the name for example if i search with the name to retrieved the hash , but how to do if i search for a hash and get the name how to take the name i stored initial there ?
Use the Contains method:
If My.Settings.md5_hashes.Contains(TextBox1.Text) = True Then
'Hash exists, do something.
Else
'Hash does not exist, do something else.
End If
Tip: Check what members IntelliSense shows you when you type My.Settings.md5_hashes. (notice the dot on the end). By doing so you would most likely have found the answer to this yourself.
EDIT:
In your specific case it gets a little more complicated because you must separate the input and the hash before you can check that the hash exists.
Try this (this is for the first code you posted in the question):
Private Function HashExists(ByVal Hash As String) As Boolean
For Each Entry As String In My.Settings.md5_hashes 'Iterate through every hash entry.
Dim Parts As String() = Entry.Split(New String() {"<--->"}, 2, StringSplitOptions.RemoveEmptyEntries) 'Split the entry on "<--->".
If Parts.Length = 1 AndAlso Parts(0) = Hash Then
Return True 'No "<--->" was present, but the entire entry matches 'Hash'.
ElseIf Parts.Length >= 2 AndAlso Parts(1) = Hash
Return True 'The entry was split successfully and the second part and 'Hash' are equal.
End If
Next
Return False 'No valid hash found.
End Function
Then use this like:
If HashExists(TextBox1.Text) = True Then
'Hash exists, do something.
Else
'Hash does not exist, do something else.
End If
EDIT 2:
To get the name from a hash or a hash from a name the above code just need to be modified slightly to return any of the two parts.
Private Function GetEntry(ByVal Input As String, ByVal NameFromHash As Boolean) As String
For Each Entry As String In My.Settings.md5_hashes 'Iterate through every hash entry.
'Parts(0) is the name.
'Parts(1) is the hash.
Dim Parts As String() = Entry.Split(New String() {"<--->"}, 2, StringSplitOptions.RemoveEmptyEntries) 'Split the entry on "<--->".
If Parts.Length >= 2 Then
If NameFromHash = True AndAlso Parts(1) = Input Then
Return Parts(0) 'Input was a valid hash, return name.
ElseIf NameFromHash = False AndAlso Parts(0) = Input Then
Return Parts(1) 'Input was a valid name, return hash.
End If
End If
Next
Return Nothing 'No valid entry found.
End Function
Usage:
'Get the name from a hash.
Dim Name As String = GetEntry(TextBox1.Text, True)
'Get the hash from a name.
Dim Hash As String = GetEntry(TextBox1.Text, False)
If the function returns Nothing that means it couldn't find the name/hash you specified. To avoid getting a NullReferenceException you can check so in an If-statement:
'Name from hash.
If Name IsNot Nothing Then
'The specified hash was found, do something with the name.
Else
'Hash not found.
MessageBox.Show("The specified hash was not found.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
'Hash from name.
If Hash IsNot Nothing Then
'The specified name was found, do something with the hash.
Else
'Name not found.
MessageBox.Show("The specified name was not found.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If