Error : file is being used by another process - vb.net

I have a problem where it says that a file is already being used by another process
But I am pretty sure it's not being used anywhere else..
Imports System.IO
Public Class Browse
Private Sub add_Click(sender As Object, e As EventArgs) Handles add.Click
Dim Files As New OpenFileDialog
Dim Folder As New FolderBrowserDialog
Dim Filelist As String = "C:\Program Files\FTP-Sync\Files.txt"
Dim FileP As String = ""
Dim list() As String = IO.File.ReadAllLines(Filelist)
If fileb.Checked Then
Try
If System.IO.File.Exists(Filelist) = True And Files.ShowDialog = Windows.Forms.DialogResult.OK Then
FileP = Files.FileName
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
If folderb.Checked Then
Try
If System.IO.File.Exists(Filelist) = True And Folder.ShowDialog = Windows.Forms.DialogResult.OK Then
FileP = Folder.SelectedPath
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End If
pathtxt.Text = FileP
End Sub
Private Sub ok_Click(sender As Object, e As EventArgs) Handles ok.Click
Dim Filelist As String = "C:\Program Files\FTP-Sync\Files.txt"
Dim writer As StreamWriter = New StreamWriter(Filelist)
Dim FileP As String = ""
Try
If pathtxt.Text = "" Then
MsgBox("No folder or file has been choosen")
Else
writer = File.AppendText(Filelist)
writer.WriteLine(pathtxt.Text)
pathtxt.Text = FileP
writer.Close()
Me.Hide()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub cancel_Click(sender As Object, e As EventArgs) Handles cancel.Click
Me.Hide()
End Sub
Private Sub Browse_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
End Class
Thanks in advance!

It was because of this:
Dim writer As StreamWriter = New StreamWriter(Filelist)
i changed it to
Dim writer As StreamWriter
and it work like a charm.. dont know if it is the right way.. but it worked.

Related

No value given for one or more required parameters while trying to access a picture file from an Acces database using VB.net

Im doing a school project. and I was testing a login form for my app. I'm trying separately from my login form and a profile pic form. I have successfully managed to save the image to the access database but I have had quite a few problems trying to display it on a textbox on my form.
This is the whole app code:
Imports System.Data.OleDb
Imports System.IO
Public Class Form2
Dim con As OleDbConnection = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\geral\source\repos\BD de imagenes\BD de imagenes\DBImagenes.mdb")
Dim cmd As New OleDbCommand
Dim sql As String
Dim da As New OleDb.OleDbDataAdapter
Dim result As Integer
Private Sub saveimage(sql As String)
Try
Dim arrimage() As Byte
Dim mstream As New System.IO.MemoryStream
PictureBox1.Image.Save(mstream, System.Drawing.Imaging.ImageFormat.Png)
arrimage = mstream.GetBuffer()
Dim Filesize As UInt32
Filesize = mstream.Length
mstream.Close()
con.Open()
cmd = New OleDbCommand
With cmd
.Connection = con
.CommandText = sql
.Parameters.AddWithValue("#Imagen", arrimage)
.Parameters.Add("#Nombre", OleDbType.VarChar).Value = TextBox1.Text
.ExecuteNonQuery()
End With
Catch ex As Exception
MsgBox(ex.Message)
Finally
con.Close()
End Try
End Sub
'End Try
Public conex As New OleDbConnection()
Public Sub conexion()
conex.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\geral\source\repos\BD de imagenes\BD de imagenes\DBImagenes.mdb"
conex.Open()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles BTNGuardar.Click
sql = "Insert into TBImg (Imagen, Nombre) Values (#Imagen, #Nombre)"
'sql = "Insert into TBImg (Imagen) Values (#Imagen)"
saveimage(sql)
MsgBox("Image has been saved in the database")
End Sub
Private Sub BtnExaminar_Click(sender As Object, e As EventArgs) Handles BtnExaminar.Click
OpenFileDialog1.Filter = "Imagenes JPG|*.jpg|Imagenes PNG|*.png"
OpenFileDialog1.RestoreDirectory = True
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
PictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName)
End If
End Sub
Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
End Sub
Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click
Try
With OpenFileDialog1
'CHECK THE SELECTED FILE IF IT EXIST OTHERWISE THE DIALOG BOX WILL DISPLAY A WARNING.
.CheckFileExists = True
'CHECK THE SELECTED PATH IF IT EXIST OTHERWISE THE DIALOG BOX WILL DISPLAY A WARNING.
.CheckPathExists = True
'GET AND SET THE DEFAULT EXTENSION
.DefaultExt = "jpg"
'RETURN THE FILE LINKED TO THE LNK FILE
.DereferenceLinks = True
'SET THE FILE NAME TO EMPTY
.FileName = ""
'FILTERING THE FILES
.Filter = "(*.jpg)|*.jpg|(*.png)|*.png|(*.jpg)|*.jpg|All files|*.*"
'SET THIS FOR ONE FILE SELECTION ONLY.
.Multiselect = False
'SET THIS TO PUT THE CURRENT FOLDER BACK TO WHERE IT HAS STARTED.
.RestoreDirectory = True
'SET THE TITLE OF THE DIALOG BOX.
.Title = "Select a file to open"
'ACCEPT ONLY THE VALID WIN32 FILE NAMES.
.ValidateNames = True
If .ShowDialog = DialogResult.OK Then
Try
PictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName)
Catch fileException As Exception
Throw fileException
End Try
End If
End With
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Exclamation, Me.Text)
End Try
End Sub
Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
conexion()
PictureBox1.SizeMode = PictureBoxSizeMode.StretchImage
End Sub
Private Sub Label1_Click(sender As Object, e As EventArgs) Handles Label1.Click
End Sub
Private Sub BtnBuscar_Click(sender As Object, e As EventArgs) Handles BtnBuscar.Click
Dim arrimage() As Byte
Dim conn As New OleDb.OleDbConnection
Dim Myconnection As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\geral\source\repos\BD de imagenes\BD de imagenes\DBImagenes.mdb"
conn.ConnectionString = Myconnection
conn.Open()
sql = "Select * from TBImg where Nombre=" & (TBBuscar.Text)
Dim cmd As New OleDbCommand
With cmd
.Connection = conex
.CommandText = sql
End With
Dim publictable As New DataTable
Try
da.SelectCommand = cmd
da.Fill(publictable)
TextBox1.Text = publictable.Rows(1).Item("Nombre").ToString
arrimage = publictable.Rows(1).Item("Imagen")
Dim mstream As New System.IO.MemoryStream(arrimage)
PictureBox1.Image = Image.FromStream(mstream)
Catch ex As Exception
MsgBox(ex.Message)
Finally
da.Dispose()
conn.Close()
End Try
End Sub
End Class
the relevant part is at Private Sub BtnBuscar_Click.
I'm trying to search in a textbox for the name that I saved the image with. but I haven't had success all I get is the error of the title.
this is how my database looks like the images are saved as an ole object
This is the error I get
I was following this tutorial https://www.youtube.com/watch?v=zFdjp39mfhQ
but he didn't quite explain how to use the:
TextBox1.Text = publictable.Rows(0).Item(1)
arrimage = publictable.Rows(0).Item(1)'
don't know if it's the cause of the issue.
instructions. The reason why my code looks different is that I was trying to stuff to see if I could make it work.
I have tried to search for answers and people suggest that I may have put the table name wrong or the column but I copied the name exactly how it is in the table with ctrl + c and ctrl + v.
what I want is that when I type the name in the column name of the database that it brings the designated picture stored as ole object onto my desired picture box on my form app.
Needless to say, I'm not that experienced with vb.net and SQL, Acces. I'm just following tutorials for being able to complete the project.
Do not declare connections or commands or datareaders at the class level. They all need to have their Dispose methods called. Using blocks will have the declare, closing and disposing even if there is an error. Streams also need Using blocks.
Defaults for an OpenFiledialog
Multiselect is False
CheckFileExists is True
CheckPathExists is True
DereferenceLinks is True
ValidateNames is True
FileName is ""
Unless you are getting paid by the line, it is unnecessary to reset these values to their defaults.
I have alerted your Filter to exclude All Files. You also had jpg appearing twice.
I declared a variable to hold the file extension, PictureFormat, of the image file so you could provide the proper parameter for ImageFormat.
When you retrieve the image field from the database it comes as an Object. To get the Byte() a DirectCast should work.
Private PictureFormat As String
Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click
FillPictureBoxFromFile()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles BTNGuardar.Click
Try
saveimage()
Catch ex As Exception
MessageBox.Show(ex.Message)
Exit Sub
End Try
MsgBox("Image has been saved in the database")
End Sub
Private cnStr As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\geral\source\repos\BD de imagenes\BD de imagenes\DBImagenes.mdb"
Private Sub saveimage()
Dim arrimage() As Byte
Using mstream As New System.IO.MemoryStream
If PictureFormat.ToLower = ".png" Then
PictureBox1.Image.Save(mstream, System.Drawing.Imaging.ImageFormat.Png)
ElseIf PictureFormat.ToLower = ".jpg" Then
PictureBox1.Image.Save(mstream, System.Drawing.Imaging.ImageFormat.Jpeg)
End If
arrimage = mstream.GetBuffer()
Dim Filesize As Long
Filesize = mstream.Length
End Using
Using con As New OleDbConnection(cnStr),
cmd As New OleDbCommand("Insert into TBImg (Imagen, Nombre) Values (#Imagen, #Nombre)", con)
With cmd
.Parameters.Add("#Imagen", OleDbType.Binary).Value = arrimage
.Parameters.Add("#Nombre", OleDbType.VarChar).Value = TextBox1.Text
con.Open()
.ExecuteNonQuery()
End With
End Using
End Sub
Private Sub BtnExaminar_Click(sender As Object, e As EventArgs) Handles BtnExaminar.Click
FillPictureBoxFromFile()
End Sub
Private Sub BtnBuscar_Click(sender As Object, e As EventArgs) Handles BtnBuscar.Click
Dim dt As DataTable
Try
dt = GetDataByName(TBBuscar.Text)
Catch ex As Exception
MessageBox.Show(ex.Message)
Exit Sub
End Try
TextBox1.Text = dt(0)("Nombre").ToString
Dim arrimage = DirectCast(dt(0)("Imagen"), Byte())
Dim mstream As New System.IO.MemoryStream(arrimage)
PictureBox1.Image = Image.FromStream(mstream)
End Sub
Private Function GetDataByName(name As String) As DataTable
Dim dt As New DataTable
Using conn As New OleDb.OleDbConnection(cnStr),
cmd As New OleDbCommand("Select * from TBImg where Nombre= #Buscar", conn)
cmd.Parameters.Add("#Buscar", OleDbType.VarChar).Value = TBBuscar.Text
conn.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function
Private Sub FillPictureBoxFromFile()
With OpenFileDialog1
.Filter = "(*.jpg)|*.jpg|(*.png)|*.png"
.RestoreDirectory = True
.Title = "Select a file to open"
If .ShowDialog = DialogResult.OK Then
PictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName)
End If
PictureFormat = Path.GetExtension(OpenFileDialog1.FileName)
End With
End Sub

How To Fetch Webpage Source simultaneously from thousands of URLs

I am attempting to load thousands of URLs into a list, then simultaneously download the webpage source of all of those URLs. I thought I had a clear understanding of how to accomplish this but it seems that the process goes 1 by 1 (which is painstakingly slow).
Is there a way to make this launch all of these URLs at once, or perhaps more than 1 at a time?
Public Partial Class MainForm
Dim ImportList As New ListBox
Dim URLList As String
Dim X1 As Integer
Dim CurIndex As Integer
Public Sub New()
Me.InitializeComponent()
End Sub
Sub MainFormLoad(sender As Object, e As EventArgs)
Try
Dim lines() As String = IO.File.ReadAllLines("C:\URLFile.txt")
ImportList.Items.AddRange(lines)
Catch ex As Exception
MessageBox.Show(ex.ToString)
Finally
label1.Text = "File Loaded"
X1 = ImportList.Items.Count
timer1.Enabled = True
If Not backgroundWorker1.IsBusy Then
backgroundWorker1.RunWorkerAsync()
End If
End Try
End Sub
Sub BackgroundWorker1DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs)
URLList = ""
For Each item As String In ImportList.Items
CheckName(item)
CurIndex = CurIndex + 1
Next
End Sub
Sub BW1_Completed()
timer1.Enabled = False
label1.Text = "Done"
End Sub
Sub CheckName(ByVal CurUrl As String)
Dim RawText As String
Try
RawText = New System.Net.WebClient().DownloadString(CurUrl)
Catch ex As Exception
MessageBox.Show(ex.ToString)
Finally
If RawText.Contains("404") Then
If URLList = "" Then
URLList = CurUrl
Else
URLList = URLList & vbCrLf & CurUrl
End If
End If
End Try
End Sub
Sub Timer1Tick(sender As Object, e As EventArgs)
label1.Text = CurIndex.ToString & " of " & X1.ToString
If Not URLList = "" Then
textBox1.Text = URLList
End If
End Sub
Sub Button1Click(sender As Object, e As EventArgs)
Clipboard.Clear
Clipboard.SetText(URLList)
End Sub
End Class

Increasing memory usage while scrolling on listview items in vb.net

In a WinForm i have two listview(lvwTemplateCategory) one is listing folders at given directory and if you select folder, other listview(lvwTemplates) shows the files under this directory. I have also one picturebox(picTemplateImage) to show preview screenshot of that file.
While i'm scrolling on that form for 2-3 folders and 9-10 files it's memory usage goes from 62 MB to 120 MB.
I don't know how to manage the memory source also i tried to implement IDisposable but not know where to implement.
P.S. I'm using VS 2017 and calling that WinForm with .Show() method.
Also if you see non-logic codes please let me know.
Option Explicit On
Option Strict On
Imports System.IO
Public Class frmCreateNewModel
Implements IDisposable
Private Sub LoadForm(sender As Object, e As EventArgs) Handles MyBase.Load
Call AddRootDatabase()
splCreateNewModel.Panel2Collapsed = True
Size = New Size(946, 800)
End Sub
Private Sub ViewLargeIcons(sender As Object, e As EventArgs) Handles cmdViewLargeIcons.Click
lvwTemplateCategory.View = View.LargeIcon
End Sub
Private Sub ViewListIcons(sender As Object, e As EventArgs) Handles cmdViewList.Click
lvwTemplateCategory.View = View.List
End Sub
Private Sub AddRootDatabase()
Try
Dim DirDB As String = My.Settings.str_db__path_tpl
Dim DirInfoDB As New DirectoryInfo(DirDB)
For Each TplDirDB As DirectoryInfo In DirInfoDB.GetDirectories
If Not (TplDirDB.Attributes And FileAttributes.Hidden) = FileAttributes.Hidden Then
cboTemplateDatabase.Items.Add(TplDirDB.Name)
End If
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub SelectRootDatabase(sender As Object, e As EventArgs) Handles cboTemplateDatabase.SelectedIndexChanged
Try
lvwTemplateCategory.Items.Clear()
lvwTemplates.Items.Clear()
Dim DirTempRootDir As String = My.Settings.str_db__path_tpl & "\" & cboTemplateDatabase.SelectedItem.ToString
Dim DirTempDbInfo As New DirectoryInfo(DirTempRootDir)
Dim lstIcon As Integer
For Each TplCatDir As DirectoryInfo In DirTempDbInfo.GetDirectories
If Not (TplCatDir.Attributes And FileAttributes.Hidden) = FileAttributes.Hidden Then
If imgIcons.Images.ContainsKey(TplCatDir.Name) = True Then
lstIcon = imgIcons.Images.IndexOfKey(TplCatDir.Name)
Else
lstIcon = imgIcons.Images.IndexOfKey("default")
End If
lvwTemplateCategory.Items.Add(TplCatDir.Name, lstIcon)
End If
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub SelectTemplateCategory(sender As Object, e As EventArgs) Handles lvwTemplateCategory.SelectedIndexChanged
If (CInt(lvwTemplateCategory.SelectedItems.Count.ToString) = 0) Then
Return
End If
Dim DirTempCatDir As String = My.Settings.str_db__path_tpl & "\" & cboTemplateDatabase.SelectedItem.ToString & "\" & lvwTemplateCategory.SelectedItems(0).Text.ToString
Dim DirTempInfo As New DirectoryInfo(DirTempCatDir)
lvwTemplates.Items.Clear()
Try
For Each TplFile As FileInfo In DirTempInfo.GetFiles
If Not (TplFile.Attributes And FileAttributes.Hidden) = FileAttributes.Hidden Then
If Path.GetExtension(TplFile.Name) = ".spck" Or Path.GetExtension(TplFile.Name) = ".buspck" Then
lvwTemplates.Items.Add(TplFile.Name)
End If
End If
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub SelectTemplate(sender As Object, e As EventArgs) Handles lvwTemplates.SelectedIndexChanged
If (CInt(lvwTemplates.SelectedItems.Count.ToString) = 0) Then
cmdQuickConfigure.Enabled = False
Return
End If
cmdQuickConfigure.Enabled = True
Dim TemplFileName As String = Path.GetFileNameWithoutExtension(lvwTemplates.SelectedItems(0).Text.ToString)
Dim DirTempDir As String = My.Settings.str_db__path_tpl & "\" & cboTemplateDatabase.SelectedItem.ToString & "\" & lvwTemplateCategory.SelectedItems(0).Text.ToString & "\" & TemplFileName
Dim imagePath As String = DirTempDir & ".png"
If File.Exists(imagePath) Then
picTemplateImage.ImageLocation = (imagePath)
picTemplateImage.SizeMode = PictureBoxSizeMode.StretchImage
picTemplateImage.Load()
Else
picTemplateImage.Image = picTemplateImage.ErrorImage
End If
txtModelName.Text = lvwTemplates.SelectedItems(0).Text.ToString
End Sub
Private Sub VisualViewControl(sender As Object, e As EventArgs) Handles cmdVisualControl.Click
If splCreateNewModel.Panel2Collapsed = False Then
splCreateNewModel.Panel2Collapsed = True
Size = New Size(946, 800)
cmdVisualControl.Text = ">>"
Else
cmdVisualControl.Text = "<<"
splCreateNewModel.Panel2Collapsed = False
Size = New Size(1300, 800)
End If
End Sub
Private Sub BrowseDirectory(sender As Object, e As EventArgs) Handles cmdBrowseDirectory.Click
Try
Dim sfd As New SelectFolderDialog With {
.Title = "Select a folder"
}
If sfd.ShowDialog(Me) = DialogResult.OK Then
txtModelDirectory.Text = sfd.FolderName
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub DialogOK(sender As Object, e As EventArgs) Handles cmdOk.Click
CreateModel()
Close()
End Sub
Private Sub DialogCancel(sender As Object, e As EventArgs) Handles cmdCancel.Click
Close()
End Sub
End Class

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

My Second BackgroundWorker won't work

I have created 2 BackgroundWorkers and my second BackgroundWorker seem to not work at all, i have placed a messagebox indicator under "Private Sub BackgroundWorker2_DoWork" and it was triggered but the codess under it were not. Here is the complete code of my BackgroundWorker that is having problems. Is there something that is causing this?
i really need 2 BackgroundWorkers for my program as it is processing tons of files which makes the application hang-up.
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Try
If BackgroundWorker2.IsBusy <> True Then
BackgroundWorker2.RunWorkerAsync()
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub BackgroundWorker2_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker2.DoWork
Dim worker1 As System.ComponentModel.BackgroundWorker = CType(sender, System.ComponentModel.BackgroundWorker)
Try
MessageBox.Show("the program was able to open me")
'this message box above was able to display but the codes below were not processed
Dim Stream As System.IO.FileStream
Dim Index As Integer = 0
Dim openFileDialog1 As New OpenFileDialog()
openFileDialog1.InitialDirectory = "D:\work\base tremble"
openFileDialog1.Filter = "txt files (*.txt)|*.txt"
openFileDialog1.FilterIndex = 2
openFileDialog1.RestoreDirectory = True
If openFileDialog1.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
Try
'This line opens the file the user selected and sets the stream object
Stream = openFileDialog1.OpenFile()
If (Stream IsNot Nothing) Then
'create the reader here and use the stream you got from the file open dialog
Dim sReader As New System.IO.StreamReader(Stream)
Do While sReader.Peek >= 0
ReDim Preserve eArray(Index)
eArray(Index) = sReader.ReadLine
RichTextBox3.Text = eArray(Index)
Index += 1
worker1.ReportProgress(Index)
'Delay(2)
Loop
Label1.Text = "0/" & eArray.Length & ""
End If
Catch Ex As Exception
MessageBox.Show(Ex.Message)
Finally
If (Stream IsNot Nothing) Then
Stream.Close()
End If
End Try
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub BackgroundWorker2_ProgressChanged(sender As System.Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker2.ProgressChanged
Try
'Label1.Text = e.ProgressPercentage.ToString()
Me.ProgressBar2.Value = e.ProgressPercentage
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub BackgroundWorker2_Completed(sender As System.Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker2.RunWorkerCompleted
Try
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
i have sperated OpenFileDialog into a different button and i processed the retreiving storing of data into the array in the backgroundworker and it works now.
Thanks for the headsup about OpenFileDialog not allowed in backgroundworker it gave me a hint.