Sending email with attachment using VB.net - vb.net

I know this is an old issue or concern but can you help me on this.
I have a source code found in the internet that can send an attachment via email. I tried it in my application but I getting this error.
System.Web.HttpException (0x8000405) Invalid mail attachment C:\File.pdf
at System.Web.Mail.MailAttachment.VerifyFile()
at System.Web.Mail.Attachment..ctor(String filename)
This is the code I found
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Imports System.Web.Mail
Public Class ReportsForm
Dim cryRpt As New ReportDocument
Dim pdfFile As String = "C:\File.pdf"
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
cryRpt.Load("Crystal Report Path here")
CrystalReportViewer1.ReportSource = cryRpt
CrystalReportViewer1.Refresh()
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Try
Dim CrExportOptions As ExportOptions
Dim CrDiskFileDestinationOptions As New _
DiskFileDestinationOptions()
Dim CrFormatTypeOptions As New PdfRtfWordFormatOptions
CrDiskFileDestinationOptions.DiskFileName = pdfFile
CrExportOptions = cryRpt.ExportOptions
With CrExportOptions
.ExportDestinationType = ExportDestinationType.DiskFile
.ExportFormatType = ExportFormatType.PortableDocFormat
.DestinationOptions = CrDiskFileDestinationOptions
.FormatOptions = CrFormatTypeOptions
End With
cryRpt.Export()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
sendMail()
End Sub
Private Sub sendMail()
Try
Dim Smtp As SmtpMail
SmtpMail.SmtpServer.Insert(0, "hostname")
Dim Msg As MailMessage = New MailMessage
Msg.To = "to address"
Msg.From = "from address"
Msg.Subject = "Crystal Report Attachment "
Msg.Body = "Crystal Report Attachment "
Msg.Attachments.Add(New MailAttachment(pdfFile))
SmtpMail.Send(Msg)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
Thank you

I think the problem is your pdf attachment file. You are going to need somewhere safe to create it. You'll create the attachment file path and name using this code:
Dim pdfFile As String = System.IO.Path.GetTempPath & "File.pdf"
If System.IO.File.Exists(pdfFile) Then My.Computer.FileSystem.DeleteFile(pdfFile)
Then you'll export the cryRpt object to a pdf file using just one line of code:
cryRpt.ExportToDisk(ExportFormatType.PortableDocFormat, pdfFile)
If no exception occurs your attachment is created and ready to be mailed.

Related

Auto attach file on email reporting program vb.net

Here is my program for auto email with manual attachments on certain time using config.ini for email username and password
Imports System.Net.Mail
Imports System.Timers
Public Class Form1
Dim file(2) As String
Dim pesan As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.Text = "Water Monitoring"
Timer1.Start()
End Sub
Public Sub kirim() 'step send e-mail manual'
Try
Dim Smtp_Server As New SmtpClient
Dim e_mail As New MailMessage()
Dim txtEmail As String
Dim txtPassword As String
txtEmail = Module1.Read_INI("GENERAL", "Email")
txtPassword = Module1.Read_INI("GENERAL", "Password")
Smtp_Server.UseDefaultCredentials = False
Smtp_Server.Credentials = New Net.NetworkCredential(txtEmail, txtPassword) 'login email'
Smtp_Server.Port = 587
Smtp_Server.Timeout = 3000000
Smtp_Server.EnableSsl = True
Smtp_Server.Host = "smtp.gmail.com"
e_mail = New MailMessage()
e_mail.From = New MailAddress(txtEmail)
e_mail.To.Add(txtTo.Text)
e_mail.Subject = txtSubject.Text
e_mail.IsBodyHtml = False
e_mail.Body = pesan
If Not txtFile1.Text = Nothing Then
Dim attach As New Attachment(txtFile1.Text)
e_mail.Attachments.Add(attach) 'attach attachment 1
End If
If Not txtFile2.Text = Nothing Then
Dim attach As New Attachment(txtFile2.Text)
e_mail.Attachments.Add(attach) 'attach attachment 2
End If
If Not txtFile3.Text = Nothing Then
Dim attach As New Attachment(txtFile3.Text)
e_mail.Attachments.Add(attach) 'attach attachment 3
End If
Smtp_Server.Send(e_mail)
MsgBox("Mail Sent")
Catch error_t As Exception
MsgBox(error_t.ToString) 'message box error
End Try
End Sub
Private Sub chckboxAuto30s_CheckedChanged(sender As Object, e As EventArgs) Handles chckboxAuto30s.CheckedChanged
If chckboxAuto30s.Checked = True Then
btnSend.Visible = False
Else
btnSend.Visible = True
End If
End Sub
Private Sub txtMessage_TextChanged(sender As Object, e As EventArgs) Handles txtMessage.TextChanged
pesan = txtMessage.Text
End Sub
Private Sub btnCancelAllAttachments_Click(sender As Object, e As EventArgs) Handles btnCancelAllAttachments.Click
txtFile1.Text = ""
txtFile2.Text = ""
txtFile3.Text = ""
file = Nothing
End Sub
Private Sub btnAddAttachments_Click(sender As Object, e As EventArgs) Handles btnAddAttachments.Click
file = Nothing
OpenFileDialog1.ShowDialog()
file = OpenFileDialog1.FileNames
txtFile1.Text = file(0)
Try
txtFile2.Text = file(1)
Catch ex As IndexOutOfRangeException
End Try
Try
txtFile3.Text = file(2)
Catch ex As IndexOutOfRangeException 'attach file attachment'
End Try
End Sub
Private Sub btnSend_Click(sender As Object, e As EventArgs) Handles btnSend.Click
kirim() 'send e-mail manual'
End Sub
Private Sub btnClearText_Click(sender As Object, e As EventArgs) Handles btnClearText.Click
txtTo.Text = ""
txtSubject.Text = ""
txtMessage.Text = ""
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Dim timerforAuto As Date
timerforAuto = CDate(timeAuto.Text)
If timerforAuto.Hour = Now.Hour And timerforAuto.Minute = Now.Minute And timerforAuto.Second = Now.Second Then
kirim()
End If
End Sub
End Class
My question is, how to setting the attachments is choosed automatically? I want to attach file automatically based on current time.
For example : i want to attach
C:\testing1.xlsx
C:\testing2.xlsx
automatically. And refresh the file if the file contents in the xlsx have changed every day.
Change your kirim() call in the timer1_tick to accept a date parameter.
Public Sub kirim(TimeKickedOff as Date) 'step send e-mail manual'
Try
Dim Smtp_Server As New SmtpClient
Dim e_mail As New MailMessage()
Dim txtEmail As String
Dim txtPassword As String
txtEmail = Module1.Read_INI("GENERAL", "Email")
txtPassword = Module1.Read_INI("GENERAL", "Password")
Smtp_Server.UseDefaultCredentials = False
Smtp_Server.Credentials = New Net.NetworkCredential(txtEmail, txtPassword) 'login email'
Smtp_Server.Port = 587
Smtp_Server.Timeout = 3000000
Smtp_Server.EnableSsl = True
Smtp_Server.Host = "smtp.gmail.com"
e_mail = New MailMessage()
e_mail.From = New MailAddress(txtEmail)
e_mail.To.Add(txtTo.Text)
e_mail.Subject = txtSubject.Text
e_mail.IsBodyHtml = False
e_mail.Body = pesan
If Not txtFile1.Text = Nothing Then
Dim attach As New Attachment(txtFile1.Text)
e_mail.Attachments.Add(attach) 'attach attachment 1
End If
If Not txtFile2.Text = Nothing Then
Dim attach As New Attachment(txtFile2.Text)
e_mail.Attachments.Add(attach) 'attach attachment 2
End If
If Not txtFile3.Text = Nothing Then
Dim attach As New Attachment(txtFile3.Text)
e_mail.Attachments.Add(attach) 'attach attachment 3
End If
Smtp_Server.Send(e_mail)
MsgBox("Mail Sent")
Catch error_t As Exception
MsgBox(error_t.ToString) 'message box error
End Try
End Sub
Change the call in timer1_tick to pass the time it was kicked off to kirim.
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Dim timerforAuto As Date
timerforAuto = CDate(timeAuto.Text)
If timerforAuto.Hour = Now.Hour And timerforAuto.Minute = Now.Minute And timerforAuto.Second = Now.Second Then
kirim(timerforAuto)
End If
End Sub
In the kirim(TimeKickedOff as Date) sub add code that tests the TimeKickedOff to the datetime you want each attachment attached to the email, for example, in the kirim sub where SomeTime = the datetime you want the file attached:
If Not txtFile3.Text = Nothing Then
if TimeKickedOff.Hour = SomeTime.Hour And TimeKickedOff.Minute = SomeTime.Minute And TimeKickedOff.Second = SomeTime.Second Then
Dim attach As New Attachment(txtFile3.Text)
e_mail.Attachments.Add(attach) 'attach attachment 3
End If
End If
To test if a file has changed, you can handle this in the timer event. Dim a static variable that contains the content of the file and check to see if the content changes every so often and if the content changes do what you need to do when that happens and load the new content into the static variable so you can keep checking for newer changes.

the cc and bcc is not working i cant send it through one of them

Imports System.Net.Mail
Imports System.IO
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
Dim mail As New MailMessage()
Dim SmtpServer As New SmtpClient(My.Settings.smtpserver)
mail.From = New MailAddress(My.Settings.from)
mail.[To].Add(My.Settings.destination)
mail.Subject = "Program"
mail.Body = "Hi this is a msg form .net application"
Dim path As String = My.Settings.desktop
Dim dir As New DirectoryInfo(path)
Dim filesInDirectory As FileInfo() = dir.GetFiles()
Dim attach As System.Net.Mail.Attachment
For Each file In filesInDirectory
attach = New System.Net.Mail.Attachment(file.FullName)
mail.Attachments.Add(attach)
Next
SmtpServer.Port = My.Settings.port
SmtpServer.Credentials = New
System.Net.NetworkCredential(My.Settings.username, My.Settings.password)
SmtpServer.EnableSsl = True
SmtpServer.Send(mail)
MsgBox("Sent Successfuly!", MsgBoxStyle.Information, "Send!")
mail.CC.Add(My.Settings.CC)
mail.Bcc.Add(My.Settings.BCC)
Catch ex As Exception
MsgBox("Failed Sending Email!", MsgBoxStyle.Critical, "Failed!")
End Try
Application.Exit()
End Sub
End Class
the cc and bcc is not working i cant send through cc nor bcc is there any problem with my codes? the user can use this cc and bcc like gmail.
Well - you are setting CC and BCC after you send the email. Thats your problem. Move the lines:
mail.CC.Add(My.Settings.CC)
mail.Bcc.Add(My.Settings.BCC)
Up to where you are setting Mail.Subject, etc.

vb.net send mail smtp and outlook error (individually)

'Variable which will send the mail
Dim obj As System.Net.Mail.SmtpClient
'Variable to store the attachments
Dim Attachment As System.Net.Mail.Attachment
'Variable to create the message to send
Dim Mailmsg As New Mail.MailMessage()
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim ol As New Outlook.Application()
Dim ns As Outlook.NameSpace
Dim fdMail As Outlook.MAPIFolder
ns = ol.GetNamespace("MAPI")
ns.Logon(, , True, True)
'creating a new MailItem object
Dim newMail As Outlook.MailItem
'gets defaultfolder for my Outlook Outbox
fdMail = ns.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderOutbox)
'assign values to the newMail MailItem
newMail = fdMail.Items.Add(Outlook.OlItemType.olMailItem)
newMail.Subject = "tesst"
newMail.Body = "test"
newMail.To = TextBox1.Text
Dim sSource As String = Application.StartupPath + "\kk.sys"
' TODO: Replace with attachment name
Dim sDisplayName As String = "kaar.jpg"
Dim sBodyLen As String = newMail.Body.Length
newMail.SaveSentMessageFolder = fdMail
newMail.Send()
Catch ex As Exception
Using writer As StreamWriter = New StreamWriter(Application.StartupPath + "\err1.txt")
writer.WriteLine(ex.ToString)
End Using
End Try
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Try
Dim SmtpServer As New SmtpClient()
Dim mail As New MailMessage()
Dim address As New MailAddress(TextBox1.Text, "Nigraan")
Dim oAttch As Mail.Attachment = New Mail.Attachment(Application.StartupPath + "\kk.sys")
SmtpServer.Credentials = New _
Net.NetworkCredential(TextBox2.Text, TextBox3.Text)
SmtpServer.Port = "587"
SmtpServer.Host = "smtp.gmail.com"
mail = New MailMessage()
mail.From = New MailAddress(TextBox2.Text)
mail.To.Add(New MailAddress(TextBox1.Text))
mail.Subject = TextBox3.Text
mail.Body = "test"
mail.Attachments.Add(oAttch)
SmtpServer.Send(mail)
Catch ex As Exception
Using writer As StreamWriter = New StreamWriter(Application.StartupPath + "\err2.txt")
writer.WriteLine(ex.ToString)
End Using
End Try
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Try
System.Diagnostics.Process.Start("mailto:" & TextBox1.Text & "?subject=" & "re:Subject" & "&body=" & "EmailBody")
Catch ex As Exception
Using writer As StreamWriter = New StreamWriter(Application.StartupPath + "\err3.txt")
writer.WriteLine(ex.ToString)
End Using
End Try
End Sub`
errors are:
err1:
System.Runtime.InteropServices.COMException (0x80004005): There must be at least one name or distribution list in the To, Cc, or Bcc box.
at Microsoft.Office.Interop.Outlook._MailItem.Send()
at WindowsApplication1.Form1.Button1_Click(Object sender, EventArgs e)
err2:
System.ArgumentException: The parameter 'address' cannot be an empty string.
Parameter name: address
at System.Net.Mail.MailAddress..ctor(String address, String displayName, Encoding displayNameEncoding)
at WindowsApplication1.Form1.Button2_Click(Object sender, EventArgs e)
When i send using a machine with visual studio both mail gets sent, when not these errors show.
i have double checked .net framework
thank you..
Try creating a variable string and set that before sending the mail
Dim ToEmail as string
ToEmail = Textbox1.text
Then set your to address first.
'assign values to the newMail MailItem
newMail.To = ToEmail
newMail = fdMail.Items.Add(Outlook.OlItemType.olMailItem)
newMail.Subject = "tesst"
newMail.Body = "test"
i got everything working,
got smtp to work by giving ssl encryption to true
got outlook to work by creating a contact and giving the contact's email id in the 'to' field
just don't save the contact if u don't want the contact to be added in outlook :D
yeyyy!!

VB.Net Background Workers in my code?

I am a bit of a noobie with vb.net and I made this application that does a lot of http requests and stream reading. But when it does this it always freezes my application.
So I did a little research and found that I could use background workers to solve this. But I have no idea where to start. So if you could look at my code and tell me where and how I can add background workers to prevent the freezing that would be awesome.
Imports mshtml
Imports System.Net
Imports System.Threading
Imports System.Text
Imports System.IO
Imports System.Web
Public Class Form1
Inherits Form
Private Delegate Sub MyDelegate(show As Boolean)
Private demoThread As System.Threading.Thread = Nothing
Private demoThread2 As System.Threading.Thread = Nothing
Private Sub ShowProgressOnThread()
Dim newProgressWindow As New Form2
newProgressWindow.Show()
End Sub
Public Function GetTableText(ByVal sHTML As String) As String
Dim myDoc As mshtml.IHTMLDocument2 = New mshtml.HTMLDocument
Dim mElement As mshtml.IHTMLElement
Dim mElement2 As mshtml.IHTMLElement
Dim mECol As mshtml.IHTMLElementCollection
'initialize the document object within the HTMLDocument class...
myDoc.close()
myDoc.open("about:blank")
'write the HTML to the document using the MSHTML "write" method...
Dim clsHTML() As Object = {sHTML}
myDoc.write(clsHTML)
clsHTML = Nothing
mElement = myDoc.body()
mECol = mElement.getElementsByTagName("TD")
Dim gData As ListViewItem
For A = 3 To mECol.length - 1 Step +6
mElement2 = mECol.item(A)
gData = Me.ListView1.Items.Add(mElement2.innerText)
mElement2 = mECol.item(A - 1)
gData.SubItems.Add(mElement2.innerText.ToUpper)
'Frm.Close()
' lstResults.Items.Add("Game : " & mElement2.innerText)
Next
End Function
Private Sub wait(ByVal interval As Integer)
Dim sw As New Stopwatch
sw.Start()
Do While sw.ElapsedMilliseconds < interval
' Allows UI to remain responsive
Application.DoEvents()
Loop
sw.Stop()
End Sub
Private Sub Button__()
Me.ResetText()
Me.ToolStripStatusLabel1.Text = "Loading..."
Me.Text = "Game Finder | By Unh0ly | Loading..."
' Me.demoThread = New Thread( _
'New ThreadStart(AddressOf Me.Loader))
' Me.demoThread.Start()
'Me.Invoke(New MethodInvoker(AddressOf Me.Loader))
'Me.Frm.Show()
'Application.Run(Frm)
Dim srchText As String
srchText = TextBox1.Text.Replace(" ", "%20")
Dim request As HttpWebRequest = HttpWebRequest.Create("****" & srchText)
'Dim response As HttpWebResponse
Dim response As HttpWebResponse = request.GetResponse()
Dim sr As System.IO.StreamReader = New System.IO.StreamReader(response.GetResponseStream())
Dim sourcecode As String = sr.ReadToEnd()
If sourcecode.Contains("<td>") Then
GetTableText(sourcecode)
Me.ResetText()
Me.Text = "Game Finder | By Unh0ly"
Me.ToolStripStatusLabel1.Text = "Done"
Call wait(2500)
Me.ToolStripStatusLabel1.Text = "Status.."
'newProgressWindow.Hide()
'newProgressWindow.Dispose()
'Form2.Refresh()
ElseIf Not sourcecode.Contains("<td>") Then
' newProgressWindow.Hide()
' Progress.Dispose()
MessageBox.Show("No Results Found For: " + TextBox1.Text)
End If
'Dim sHTML = sourcecode
'For I = 2 To mECol.length - 1 Step +6
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
'Frm.Show()
Me.Invoke(New MethodInvoker(AddressOf Button__))
'Dim demoThread As System.Threading.Thread
End Sub
Private Sub CopyToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles CopyToolStripMenuItem.Click, IDAndGameNameToolStripMenuItem.Click
Try
Dim s As String
Dim lsvrow
lsvrow = ListView1.SelectedItems(0)
s = "Game Name: " + lsvrow.Text + ControlChars.NewLine + "ID: " + TextBox2.Text
Clipboard.SetDataObject(s)
Catch ex As System.Exception
MessageBox.Show("Error: " + ex.Message)
Finally
' Perform any tidy up code.
End Try
End Sub
Private Sub CopyIDToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles CopyIDToolStripMenuItem.Click, IDToolStripMenuItem.Click
Try
Dim s As String
Dim lsvrow
lsvrow = ListView1.SelectedItems(0)
s = TextBox2.Text
Clipboard.SetDataObject(s)
Catch ex As System.Exception
MessageBox.Show("Error: " + ex.Message)
Finally
' Perform any tidy up code.
End Try
End Sub
Private Sub ListView1_ItemActivate(sender As System.Object, e As System.Windows.Forms.ListViewItemSelectionChangedEventArgs) Handles ListView1.ItemSelectionChanged
TextBox2.Text = e.Item.SubItems(1).Text
End Sub
Private Sub TextBox1_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
If e.KeyCode = Keys.Enter Then
'Runs the Button1_Click Event
Button1_Click(Me, EventArgs.Empty)
End If
End Sub
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click, ClearToolStripMenuItem.Click
ListView1.Items.Clear()
End Sub
Private Sub DownloadGPDToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles DownloadGPDToolStripMenuItem.Click, DownloadGPDToolStripMenuItem1.Click
Dim gpds As ArrayList = New ArrayList()
Const YOUR_DIRECTORY As String = "****"
' Get the object used to communicate with the server.
Dim request As FtpWebRequest = CType(WebRequest.Create(YOUR_DIRECTORY), FtpWebRequest)
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails
' This example assumes the FTP site uses anonymous logon.
request.Credentials = New NetworkCredential("****", "****")
Call wait(1500)
Dim response As FtpWebResponse = CType(request.GetResponse, FtpWebResponse)
Dim responseStream As Stream = response.GetResponseStream
Dim reader As StreamReader = New StreamReader(responseStream)
Dim s = reader.ReadToEnd
reader.Close()
response.Close()
If Len(TextBox2.Text) > 0 Then
If s.Contains(TextBox2.Text + ".gpd") Then
FolderBrowserDialog1.ShowDialog()
If Not FolderBrowserDialog1.SelectedPath = Nothing Then
Me.Text = "Game Finder | By Unh0ly | Downloading..."
Me.ToolStripStatusLabel1.Text = "Downloading..."
My.Computer.Network.DownloadFile("****" + TextBox2.Text + ".gpd", FolderBrowserDialog1.SelectedPath + "\" + TextBox2.Text + ".gpd", "", "", False, "100", True)
Me.ResetText()
Me.ToolStripStatusLabel1.Text = "Status.."
ElseIf FolderBrowserDialog1.SelectedPath = Nothing Then
Else
MessageBox.Show("No GPD for Selected Game")
End If
Else
MessageBox.Show("No GPD for Selected Game")
End If
Else
' Do Nothing
End If
End Sub
Private Sub ExitToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles ExitToolStripMenuItem.Click
Application.Exit()
End Sub
Private Sub CheckForUpdatesToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles CheckForUpdatesToolStripMenuItem.Click
Dim request As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create("****")
Dim response As System.Net.HttpWebResponse = request.GetResponse()
Dim sr As System.IO.StreamReader = New System.IO.StreamReader(response.GetResponseStream())
Dim newestversion As String = sr.ReadToEnd()
Dim currentversion As String = Application.ProductVersion
Dim request1 As System.Net.HttpWebRequest = System.Net.HttpWebRequest.Create("****")
Dim response1 As System.Net.HttpWebResponse = request1.GetResponse()
Dim sr1 As System.IO.StreamReader = New System.IO.StreamReader(response1.GetResponseStream())
Dim updurl As String = sr1.ReadToEnd()
If newestversion.Contains(currentversion) Then
MessageBox.Show("You have the current version", "Up to date", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
Dim result1 As DialogResult = MessageBox.Show("Newer version available" & vbCrLf & "Please Goto *** to check" + vbCrLf + "Do you want to go there now?", "Update Available", MessageBoxButtons.YesNo, MessageBoxIcon.Information)
If result1 = DialogResult.Yes Then
Process.Start(updurl)
Else
' Do Nothing
End If
End If
End Sub
Private Sub AboutToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles AboutToolStripMenuItem.Click
Dim gpds As ArrayList = New ArrayList()
Const YOUR_DIRECTORY As String = "****"
Dim request As FtpWebRequest = CType(WebRequest.Create(YOUR_DIRECTORY), FtpWebRequest)
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails
request.Credentials = New NetworkCredential("****", "****")
Call wait(100)
Dim response As FtpWebResponse = CType(request.GetResponse, FtpWebResponse)
Dim responseStream As Stream = response.GetResponseStream
Dim reader As StreamReader = New StreamReader(responseStream)
Dim s = reader.ReadToEnd
reader.Close()
response.Close()
Dim Lines() As String = s.Split(New String() {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
MessageBox.Show("Made By Unh0ly aka Nickdudego3" & vbCrLf & "Number of GPD's: " & Lines.Length - 5 & vbCrLf & "Version: " & Application.ProductVersion, "About", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
End Sub
End Class
Here's a small sample how to use a worker..
Friend WithEvents myWorker As System.ComponentModel.BackgroundWorker
Me.myWorker = New System.ComponentModel.BackgroundWorker()
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
myWorker.RunWorkerAsync()
End Sub
Private Sub myWorker_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles myWorker.DoWork
'do your stuff here...
End Sub
The best way to find bottle neck in your code is to put Timer.Start and Timer.Stop around your methods to find out which methods are taking the longest to excute.
Once you find the offending methods, you can use ThreadPool.QueueUserWorkItem to implement a basic background threading. Threading is by no means easy and it would take some time for you figure it out all the crazy and weird things that happen when you play with threads.
Hope this helps. If you have any more question, do ask.

Delete an image from folder using filename in vb.net

I have backup folder where I store the images while loading them. So I need to delete the image from the backup folder when deleted from the checked listbox.
So how do I do that?
If CheckedListBox1.Items.Count = 0 Then
MsgBox("Please load the images", MsgBoxStyle.Critical)
Else
If Thumbcontrol1.SelectedThumbnail Is Nothing Then
MsgBox("Please select the thumbnail to remove", MsgBoxStyle.Information)
Else
CheckedListBox1.Items.Remove(CheckedListBox1.SelectedItem)
Thumbcontrol1.RemoveSelectedThumbnail()
If CheckedListBox1.Items.Count > 0 Then
CheckedListBox1.SelectedIndex = CInt(index)
End If
If CheckedListBox1.Items.Count = 0 Then
Thumbcontrol1.BackgroundImage = My.Resources.backimage
frmDisplay.GCanvas1.Image = Nothing
End If
End If
End If
You can use the methods in the System.IO.File class to delete a file, by providing the filepath to the method.
System.IO.File.Delete("path\to\file")
System.IO.File.Delete(filename)
Imports System.Data.OleDb
Public Class Form2
Dim cn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Application.StartupPath & "\dv.accdb;")
Dim cm As New OleDbCommand
Dim bytImage() As Byte
Private Sub btnbrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnbrowse.Click
Dim dialog As New OpenFileDialog()
dialog.Title = "Browse Picture"
dialog.Filter = "Image Files(*.BMP;*.JPG;*.GIF;*.PNG)|*.BMP;*.JPG;*.GIF;*.PNG"
If dialog.ShowDialog() = Windows.Forms.DialogResult.OK Then
PictureBox1.Image = Image.FromFile(dialog.FileName)
End If
End Sub
Private Sub btnsave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnsave.Click
Try
Dim ms As New System.IO.MemoryStream
Dim bmpImage As New Bitmap(PictureBox1.Image)
bmpImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg)
bytImage = ms.ToArray()
ms.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
cn.Open()
cm.Connection = cn
cm.CommandType = CommandType.Text
cm.CommandText = "INSERT INTO `pic1` (pic) VALUES (#image)"
cm.Parameters.AddWithValue("#image", bytImage)
cm.ExecuteNonQuery()
cn.Close()
MsgBox("Image Saved.")
End Sub