VB.net Multiple StreamReader and FileStream in a single button - vb.net

I want to create multiple of these readers but my program only reads the first filestream is there a way for it to read them all? or do i have to place them in different buttons? here is my current code, :
Public aRecp As String()
Public listRecp As New List(Of String)
Public aEmail As String()
Public listEmail As New List(Of String)
Public aName As String()
Public listName As New List(Of String)
Public sArray As String()
Public sList As New List(Of String)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim fStream As New System.IO.FileStream("messages.txt", IO.FileMode.Open)
Dim sReader As New System.IO.StreamReader(fStream)
Dim Index As Integer = 0
Do While sReader.Peek >= 0
sList.Add(sReader.ReadLine)
Loop
sArray = sList.ToArray
fStream.Close()
sReader.Close()
Dim StreamName As New System.IO.FileStream("sendername.txt", IO.FileMode.Open)
Dim ReaderName As New System.IO.StreamReader(StreamName)
Dim IndexName As Integer = 0
Do While ReaderName.Peek >= 0
listName.Add(sReader.ReadLine)
Loop
aName = listName.ToArray
StreamName.Close()
ReaderName.Close()
Dim StreamEmail As New System.IO.FileStream("senderemail.txt", IO.FileMode.Open)
Dim ReaderEmail As New System.IO.StreamReader(StreamEmail)
Dim IndexEmail As Integer = 0
Do While ReaderEmail.Peek >= 0
listEmail.Add(sReader.ReadLine)
Loop
aEmail = listEmail.ToArray
StreamEmail.Close()
ReaderEmail.Close()
Dim StreamRecp As New System.IO.FileStream("recpname.txt", IO.FileMode.Open)
Dim ReaderRecp As New System.IO.StreamReader(StreamRecp)
Dim IndexRecp As Integer = 0
Do While ReaderRecp.Peek >= 0
listRecp.Add(ReaderRecp.ReadLine)
Loop
aRecp = listRecp.ToArray
StreamRecp.Close()
ReaderRecp.Close()
End Sub

Not a direct answer to your question (and there's nothing obvious to me in your posted code as to why it's only executing the first reader), but since you're reading text files it'd be a lot less code to use File.ReadAllLines(fileName), like this:
Public aRecp As String()
Public aEmail As String()
Public aName As String()
Public sArray As String()
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
sArray = File.ReadAllLines("messages.txt")
aName = File.ReadAllLines("sendername.txt")
aEmail = File.ReadAllLines("senderemail.txt")
aRecp = File.ReadAllLines("recpname.txt")
End Sub
File.ReadAllLines(fileName) returns an array that has each line of the text file as an element. Much simpler than creating the stream, peeking your way through and reading each line into a list and then converting it to an array.

Related

Load multiple files by File-Type into ListView Control

How I can load files by File-Type?
I only wanna load the video files(.ts) from first the Loop and (.srt) files in the second Loop.
I tried, but I can't succeed in setting the Filter.
Here's the code by jmcilhinney
Private Sub tbnAddFiles_Click(sender As Object, e As EventArgs) Handles tbnAddFiles.Click
Dim vPaths As New List(Of String)
Dim vNames As New List(Of String)
Dim sPaths As New List(Of String)
Dim sNames As New List(Of String)
Dim x As New OpenFileDialog
x.Multiselect = True
x.Filter = "TS and SRT File|*.ts;*.srt"
x.RestoreDirectory = True
If x.ShowDialog = DialogResult.OK Then
'FOR VIDEO FILES (.ts)
For Each f In x.FileNames
vNames.Add(f)
vPaths.Add(Path.GetFileName(f))
Next
'FOR SRT FILES (.srt)
For Each f2 In x.FileNames
sNames.Add(f2)
sPaths.Add(Path.GetFileName(f2))
Next
AddToListView(vNames.ToArray, vPaths.ToArray, sNames.ToArray, sPaths.ToArray)
End If
End Sub
Sub AddToListView(vNames As String(), sNames As String(), vPaths As String(), sPaths As String())
LV.Items.Clear()
Dim items As New List(Of ListViewItem)
Dim upperBounds = {vNames.GetUpperBound(0), sNames.GetUpperBound(0), vPaths.GetUpperBound(0), sPaths.GetUpperBound(0)}
For i = 0 To upperBounds.Min
items.Add(New ListViewItem({vNames(i), sNames(i), vPaths(i), sPaths(i)}))
Next
LV.BeginUpdate()
LV.Items.AddRange(items.ToArray())
LV.EndUpdate()
End Sub
Filter the list using LINQ:
For Each f In x.FileNames.Where(Function(s) Path.GetExtension(s) = ".ts")
vNames.Add(f)
vPaths.Add(Path.GetFileName(f))
Next
'FOR SRT FILES (.srt)
For Each f In x.FileNames.Where(Function(s) Path.GetExtension(s) = ".srt")
sNames.Add(f)
sPaths.Add(Path.GetFileName(f))
Next
Here's the fixed and updated codes.
Big thanks to #jmcilhinney
Private Sub btnAddFiles_Click(sender As Object, e As EventArgs) Handles btnAddFiles.Click
Using ofd As New OpenFileDialog
With ofd
.Filter = ("video and srt files (*.ts;*.srt)|*.ts;*.srt")
.Multiselect = True
.RestoreDirectory = True
End With
If ofd.ShowDialog = DialogResult.OK Then
Dim vPaths As New List(Of String)
Dim sPaths As New List(Of String)
Dim vNames As New List(Of String)
Dim sNames As New List(Of String)
Dim oNames As New List(Of String)
txtinputFolder.Text = Path.GetDirectoryName(ofd.FileName)
For Each vid In ofd.FileNames.Where(Function(s) Path.GetExtension(s) = ".ts")
vNames.Add(vid) 'input paths
vPaths.Add(Path.GetFileName(vid)) 'intput filenames
oNames.Add(Path.GetFileNameWithoutExtension(vid) & ".mkv") 'output file name
Next
For Each srt In ofd.FileNames.Where(Function(s) Path.GetExtension(s) = ".srt")
sNames.Add(srt) 'input paths
sPaths.Add(Path.GetFileName(srt)) 'input filenames
Next
AddToListView(vPaths.ToArray, sPaths.ToArray, oNames.ToArray, vNames.ToArray, sNames.ToArray)
End If
End Using
End Sub
Sub AddToListView(vPaths As String(), sPaths As String(), vNames As String(), sNames As String(), oNames As String())
LV.Items.Clear()
Dim items As New List(Of ListViewItem)
Dim upperBounds = {vPaths.GetUpperBound(0), sPaths.GetUpperBound(0), vNames.GetUpperBound(0), sNames.GetUpperBound(0), oNames.GetUpperBound(0)}
For i = 0 To upperBounds.Min
items.Add(New ListViewItem({"Queued", vPaths(i), sPaths(i), vNames(i), sNames(i), oNames(i)}))
Next
LV.BeginUpdate()
LV.Items.AddRange(items.ToArray())
LV.EndUpdate()
updateParameter()
End Sub

How to compare if a certain value all ready exist on my.settings vb.net

How to compare if a certain value all ready exist on my.settings vb.net
Hi i have start a new application and i have the application all much finish but i can not find the way to verify if a certain value its present on my.settings.md5_hashes .
So my application on the first form you can hash a string of each line on my text file and the insert is name and after the name its value.
My question is well i know how to retrieved the values and list the again on a listbox but how can i look if a certain string its exists?
this is my code
Imports System.IO
Imports System.Security.Cryptography
Imports System.Text
Public Class Form2
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If My.Settings.md5_hashes Is Nothing Then My.Settings.md5_hashes = New System.Collections.Specialized.StringCollection()
Dim openfile = New OpenFileDialog()
openfile.Filter = "Text (*.txt)|*.txt"
If (openfile.ShowDialog() = System.Windows.Forms.DialogResult.OK) Then
Dim myfile As String = openfile.FileName
Dim allLines As String() = File.ReadAllLines(myfile)
For Each line As String In allLines
'ListBox1.Items.Add(line)
Using hasher As MD5 = MD5.Create() ' create hash object
' Convert to byte array and get hash
Dim dbytes As Byte() =
hasher.ComputeHash(Encoding.UTF8.GetBytes(line))
' sb to create string from bytes
Dim sBuilder As New StringBuilder()
' convert byte data to hex string
For n As Integer = 0 To dbytes.Length - 1
sBuilder.Append(dbytes(n).ToString("X2"))
Next n
ListBox1.Items.Add(line + "<--->" + sBuilder.ToString)
My.Settings.md5_hashes.Add(line)
My.Settings.md5_hashes.Add(sBuilder.ToString)
My.Settings.Save()
End Using
Next
End If
For Each item In My.Settings.md5_hashes
ListBox1.Items.Add(item)
Next
If My.Settings.md5_hashes Is Nothing Then
Return
End If
MsgBox("All Imported Hashed And saved!")
ListBox1.Items.Clear()
End Sub
Shared Function GetHash(theInput As String) As String
Using hasher As MD5 = MD5.Create() ' create hash object
' Convert to byte array and get hash
Dim dbytes As Byte() =
hasher.ComputeHash(Encoding.UTF8.GetBytes(theInput))
' sb to create string from bytes
Dim sBuilder As New StringBuilder()
' convert byte data to hex string
For n As Integer = 0 To dbytes.Length - 1
sBuilder.Append(dbytes(n).ToString("X2"))
Next n
Return sBuilder.ToString()
End Using
End Function
Private Sub ListBox2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox2.SelectedIndexChanged
End Sub
End Class
Try something like below. I threw in a "GetStoredHash()" function, but it's not being used; thought you'll need one of those eventually, though:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If My.Settings.md5_hashes Is Nothing Then
My.Settings.md5_hashes = New System.Collections.Specialized.StringCollection()
End If
Dim openfile As New OpenFileDialog()
openfile.Filter = "Text (*.txt)|*.txt"
If (openfile.ShowDialog() = System.Windows.Forms.DialogResult.OK) Then
Dim strHash As String
For Each line As String In File.ReadAllLines(openfile.FileName)
If Not IsValuePresent(line) Then ' prevent duplicates from being added to you collection
strHash = GetHash(line)
ListBox1.Items.Add(line + "<--->" + strHash)
My.Settings.md5_hashes.Add(line)
My.Settings.md5_hashes.Add(strHash)
My.Settings.Save()
End If
Next
End If
MessageBox.Show("All Imported Hashed And saved!")
ListBox1.Items.Clear()
End Sub
Public Function GetHash(ByVal theInput As String) As String
Static hasher As MD5 = MD5.Create() ' create and KEEP hash object so it can be re-used
Static sBuilder As New StringBuilder() ' sb to create string from bytes
' convert byte data to hex string
sBuilder.Clear()
For Each dbyte As Byte In hasher.ComputeHash(Encoding.UTF8.GetBytes(theInput))
sBuilder.Append(dbyte.ToString("X2"))
Next
Return sBuilder.ToString()
End Function
Private Function IsValuePresent(ByVal value As String) As Boolean
If My.Settings.md5_hashes Is Nothing Then
My.Settings.md5_hashes = New System.Collections.Specialized.StringCollection()
End If
Return My.Settings.md5_hashes.Contains(value)
End Function
Private Function GetStoredHash(ByVal value As String) As String
If My.Settings.md5_hashes Is Nothing Then
My.Settings.md5_hashes = New System.Collections.Specialized.StringCollection()
End If
Dim index As Integer = My.Settings.md5_hashes.IndexOf(value)
If index <> -1 AndAlso (index + 1) < My.Settings.md5_hashes.Count Then
Return My.Settings.md5_hashes.Item(index + 1)
End If
Return ""
End Function

Read each number from array and making sum

I am kinda new at coding.
I am reading some numbers from a txt files and i have them into a array,i managed to make them descending,now i want to make a sum with this numbers,for example:
I will have an input number 1000,on the list i will have numbers from 100 to 1000 and i want to make a sum with them to reach 1000 with minimum rest.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim fStream As New System.IO.FileStream("C:\Users\Alex\Desktop\test.txt", IO.FileMode.Open)
Dim sReader As New System.IO.StreamReader(fStream)
Dim List As New List(Of Double)
Do While sReader.Peek >= 0
List.Add(sReader.ReadLine)
Loop
Dim i As Long
Dim txt As String
Dim thisArray As Double() = List.ToArray
For i = LBound(thisArray) To UBound(thisArray)
txt = thisArray(i) & vbCrLf
Next i
Array.Sort(thisArray)
For j As Integer = 0 To thisArray.Count - 1
Dim FILE_NAME As String = "C:\Users\Alex\desktop\test2.txt"
If System.IO.File.Exists(FILE_NAME) = True Then
Dim objWriter As New System.IO.StreamWriter(FILE_NAME, IO.FileMode.Append)
objWriter.WriteLine(thisArray(j))
objWriter.Close()
Else
MessageBox.Show("File Does Not Exist")
End If
Next
fStream.Close()
sReader.Close()
End Sub
I dont know where to start to do this..input number will be from a textbox.

Putting custom list in datagridview vb.net

I have following structure
matrix As Dictionary(Of String, Dictionary(Of Class1, Class2))
I would like to put all the elements of this structure in a datagridview like this:
Column1: String | Column2: Class1.name | column3: class2.name
Anyone have a clue on how to pull this off? I am new to datagridviews so have no clue on how to start adding rows and colums (maybe autogenerate the columns??)
Tested and working sample:
Public Class Class1
Public name As String
End Class
Public Class Class2
Public name As String
End Class
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim matrix As New Dictionary(Of String, Dictionary(Of Class1, Class2))
matrix.Add("hello", New Dictionary(Of Class1, Class2))
matrix("hello").Add(New Class1 With {.name = "123"}, New Class2 With {.name = "321"})
Dim dt As New DataTable
With dt.Columns
.Add("Column1")
.Add("Column2")
.Add("Column3")
End With
For i = 0 To matrix.Count - 1
Dim key As String = matrix.Keys(i)
Dim value As Dictionary(Of Class1, Class2) = matrix.Values(i)
For j = 0 To value.Count - 1
Dim class1Name As String = value.Keys(j).name
Dim class2Name As String = value.Values(j).name
Dim dr As DataRow = dt.NewRow
With dr
.Item("Column1") = key
.Item("Column2") = class1Name
.Item("Column3") = class2Name
End With
dt.Rows.Add(dr)
Next
Next
dataGridView1.DataSource = dt
End Sub

Empty ControlCollection at Runtime

I can't find an answer to this anywhere. I define a new instance of a forms control collection, but at runtime, the collection is empty. It works for one load button on the form, but not another. The code is exactly the same, but one works, the other doesn't. Here is the relevant code:
Private Sub miFLoad_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles miFLoad.Click
Dim FilePath As String = "C:\FList\FList.flt"
Dim LoadFile As New SaveandLoad.SaveAndLoad
Dim FileRead As New Simple3Des("MyPassword")
Dim FileString As String = FileRead.ReadFile(FilePath)
With LoadFile
.WhichList = dgFList
.FilePath = FilePath
.DecryptedString = FileRead.DecryptData(FileString)
End With
Call LoadFile.LoadFile()
End Sub
This load button not loading
Private Sub miCLoad_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles miCLoad.Click
Dim FilePath As String = "C:\FList\CList.clt"
Dim LoadFile As New SaveandLoad.SaveAndLoad
Dim FileRead As New Simple3Des("MyPassword")
Dim FileString As String = FileRead.ReadFile(FilePath)
With LoadFile
.WhichList = dgCourses
.FilePath = FilePath
.DecryptedString = FileRead.DecryptData(FileString)
End With
Call LoadFile.LoadFile()
End Sub
This one is.
Public Sub LoadFile()
Dim dgRow As DataGridViewRow
Dim dgCell As DataGridViewTextBoxCell
Dim Lines() As String = DecryptedString.Split(vbLf)
Dim LinesList As List(Of String) = Lines.ToList
LinesList.RemoveAt(Lines.Length - 1)
For Each Line As String In LinesList
Dim Fields() As String = Line.Split(",")
dgRow = New DataGridViewRow
For x = 0 To (WhichList.Columns.Count - 1) Step 1
dgCell = New DataGridViewTextBoxCell
dgCell.Value = Fields(x).ToString
dgRow.Cells.Add(dgCell)
Next
WhichList.Rows.Add(dgRow)
Next
Dim FormControls As New frmFacultyList.ControlCollection(frmFacultyList)
For Each DGV As DataGridView In FormControls
If WhichList.Name = DGV.Name Then
DGV = WhichList
DGV.Refresh()
End If
Next
End Sub
Here is where they pass the info to. Again, the FormControls variable is empty for FLoad button click, but not for CLoad button click. Any help would be appreciated.
Edit: Sorry, here are the relevant Public Properties
Public Property WhichList As New DataGridView
Public Property FilePath As String
Public Property DecryptedString As String
Public Property EncryptedString As String
Turns I solved my own problem. The Save Function wasn't writing to the file correctly, so it wasn't pulling the information correctly. Fixed.