How to search an FTP ListDirectory for a pattern to download specific files - vb.net

I am working on a download feature for my GUI that will allow the end user to be able to input a 5 digit job number and download only those files from the FTP site. In doing this, I have been able to get a list of the directory, but I have not been able to use that list to get the files. Any help on the code shown would be appreciated.
Dim UserName As String
' Sets Username to current logged-in user profile
UserName = Environment.UserName
Dim JobNo As String
JobNo = Textbox1.Text
Dim listRequest As FtpWebRequest = WebRequest.Create("ftp://ftp.site.com/INPUT/" & JobNo & "_*.DBF")
listRequest.Credentials = New System.Net.NetworkCredential(“Username”, “Password”)
listRequest.Method = WebRequestMethods.Ftp.ListDirectory
Dim listResponse As FtpWebResponse = listRequest.GetResponse()
Dim reader As StreamReader = New StreamReader(listResponse.GetResponseStream())
For Each foundFile As String In
My.Computer.Network.DownloadFile("ftp://ftp.site.com/INPUT/" & foundFile, "C:\users\” & UserName & “\desktop\temp\" & foundFile, “Username”, “Password”)
Next

Below is the final output that worked. The overall
Dim UserName As String
' Sets Username to current logged-in user profile
UserName = Environment.UserName
Dim JobNo As String
JobNo = Textbox1.Text
'DOWNLOADING FROM THE FTP JOBS PROCESSED FOLDER
Dim listRequest As FtpWebRequest = WebRequest.Create(“ftp.site.com/input/” & JobNo & "_*.DBF")
listRequest.Credentials = New System.Net.NetworkCredential(“Username”, “Password”)
listRequest.Method = WebRequestMethods.Ftp.ListDirectory
Dim listResponse As FtpWebResponse = listRequest.GetResponse()
Dim reader As StreamReader = New System.IO.StreamReader(listResponse.GetResponseStream())
Dim Filedata As String = reader.ReadToEnd
Dim directory() As String = Filedata.Split(New String() {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
'CREATES TEAM FILE FOLDERS ON LOCAL COMPUTER
My.Computer.FileSystem.CreateDirectory("C:\users\" & UserName & "\desktop\TEAMFILES\IMB_APPEND\A_TEAM")
My.Computer.FileSystem.CreateDirectory("C:\users\" & UserName & "\desktop\TEAMFILES\IMB_APPEND\B_TEAM")
'CLEAR TEXTBOX2
TextBox2.Clear()
For Each foundFile As String In directory
ATEAMdown(foundFile)
TextBox2.Text = TextBox2.Text & foundFile & vbNewLine
Next
'DOWNLOADING FROM THE IMB FTP XMPIE TEAM FOLDER
listRequest = WebRequest.Create(“ftp.site.com/input/” & JobNo & "_*.DBF")
listRequest.Credentials = New System.Net.NetworkCredential(“Username”, “Password”)
listRequest.Method = WebRequestMethods.Ftp.ListDirectory
listResponse = listRequest.GetResponse()
reader = New System.IO.StreamReader(listResponse.GetResponseStream())
Filedata = reader.ReadToEnd
directory = Filedata.Split(New String() {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
For Each foundFile As String In directory
BTEAMdown(foundFile)
TextBox2.Text = TextBox2.Text & foundFile & vbNewLine
Next

I was trying to download files from the FTP based on the list that was created using ListDirectory, but it was not split in a usable format from the reader and therefore could not be used I have updated my code and have it working:
Dim UserName As String
' Sets Username to current logged-in user profile
UserName = Environment.UserName
Dim JobNo As String
JobNo = Textbox1.Text
Dim listRequest As FtpWebRequest = WebRequest.Create("ftp://ftp.site.com/INPUT/" & JobNo & "_*.DBF")
listRequest.Credentials = New System.Net.NetworkCredential(“Username”, “Password”)
listRequest.Method = WebRequestMethods.Ftp.ListDirectory
Dim listResponse As FtpWebResponse = listRequest.GetResponse()
Dim reader As StreamReader = New System.IO.StreamReader(listResponse.GetResponseStream())
Dim Filedata As String = reader.ReadToEnd
Dim directory() As String = Filedata.Split(New String() {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
For Each foundFile As String In directory
My.Computer.Network.DownloadFile("ftp://ftp.site.com/INPUT/" & foundFile, "C:\users\” & UserName & “\desktop\temp\" & foundFile, “Username”, “Password”)
Next
Updated Section
Dim reader As StreamReader = New System.IO.StreamReader(listResponse.GetResponseStream())
Dim Filedata As String = reader.ReadToEnd
Dim directory() As String = Filedata.Split(New String() {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)

Related

how to add filters on vb HttpWebRequest

This code, is working perfectly (getting data with web request) :
Protected Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim oauth_token = "8e269b44b2d7d73eb0b46112af5f4xxx"
Dim oauth_token_secret = "80da1edadcba1e66e47d2e20f075cxxx"
Dim oauth_consumer_key = "3626311748bcf2072da2bd475fccfxxx"
Dim oauth_consumer_secret = "0cbb0df8d840e22b96d4f80449e7exxx"
Dim oauth_version = "1.0"
Dim oauth_signature_method = "HMAC-SHA1"
Dim oauth_nonce = Convert.ToBase64String(New ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()))
Dim timeSpan = DateTime.UtcNow - New DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)
Dim oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString()
Dim resource_url = "http://www.inart.com/api/rest/products/store/1"
Dim baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" + "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}"
Dim baseString = String.Format(baseFormat, oauth_consumer_key, oauth_nonce, oauth_signature_method, oauth_timestamp, oauth_token, oauth_version)
baseString = String.Concat("GET&", Uri.EscapeDataString(resource_url), "&", Uri.EscapeDataString(baseString))
Dim compositeKey = String.Concat(Uri.EscapeDataString(oauth_consumer_secret), "&", Uri.EscapeDataString(oauth_token_secret))
Dim oauth_signature As String
Using hasher As New HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey))
oauth_signature = Convert.ToBase64String(hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)))
End Using
Dim headerFormat = "OAuth oauth_nonce=""{0}"", oauth_signature_method=""{1}"", " + "oauth_timestamp=""{2}"", oauth_consumer_key=""{3}"",
" + "oauth_token=""{4}"", oauth_signature=""{5}"", " + "oauth_version=""{6}"""
Dim authHeader = String.Format(headerFormat, Uri.EscapeDataString(oauth_nonce), Uri.EscapeDataString(oauth_signature_method), Uri.EscapeDataString(oauth_timestamp),
Uri.EscapeDataString(oauth_consumer_key), Uri.EscapeDataString(oauth_token), Uri.EscapeDataString(oauth_signature), Uri.EscapeDataString(oauth_version))
ServicePointManager.Expect100Continue = True
Dim request As HttpWebRequest = DirectCast(WebRequest.Create(resource_url), HttpWebRequest)
request.Headers.Add("Authorization", authHeader)
request.Method = "GET"
request.ContentType = "application/json"
request.Accept = "application/json"
Try
Dim response As WebResponse = request.GetResponse()
Dim datastream As Stream = response.GetResponseStream
Dim reader As StreamReader = New StreamReader(datastream)
Dim responsefromserver As String = reader.ReadToEnd
If responsefromserver = Nothing Then
TextBox1.Text = "No response from server"
Else
Dim json As String = responsefromserver
Dim ser As JObject = JObject.Parse(json)
Dim data As List(Of JToken) = ser.Children().ToList
Dim output As String = ""
Dim successReq As Boolean = False
Dim avDom As String = ""
Dim counter As Integer = 0
For Each item As JProperty In data
item.CreateReader()
output += "|-" & item.Name.ToString & " : " & item.Value.ToString & "-"
output += Environment.NewLine
counter += 1
Next
TextBox1.Text = output
TextBox1.Text += Environment.NewLine + counter.ToString
reader.Close()
response.Close()
End If
Catch ex As Exception
TextBox1.Text = ex.Message.ToString
End Try
End Sub
When i try to add some filters, it fails. for example, I try to add the limit filter this way : Dim resource_url = "http://www.inart.com/api/rest/products/store/1?limit=1".
I am sure that the filter is ok because i tried at postman application and it is working! see print screen
What should I change or add?
Thank you.
Dim url As String = "http://www.inart.com/api/rest/products/store/1?limit=1&page=2"
Dim oauthconsumerkey As String = "3626311748bcf2072da2bd475fccssss"
Dim oauthconsumersecret As String = "0cbb0df8d840e22b96d4f80449sssss"
Dim oauthtoken As String = "8e269b44b2d7d73essss2af5f454e"
Dim oauthtokensecret As String = "80da1edadcba1e66e47d2e2sssss"
Dim oauthsignaturemethod As String = "HMAC-SHA1"
Dim oauthversion As String = "1.0"
Dim oauthnonce As String = Convert.ToBase64String(New ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()))
Dim timeSpan As TimeSpan = DateTime.UtcNow - New DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)
Dim oauthtimestamp As String = Convert.ToInt64(timeSpan.TotalSeconds).ToString()
Dim basestringParameters As SortedDictionary(Of String, String) = New SortedDictionary(Of String, String)()
basestringParameters.Add("limit", "1")
basestringParameters.Add("page", "2")
basestringParameters.Add("oauth_version", oauthversion)
basestringParameters.Add("oauth_consumer_key", oauthconsumerkey)
basestringParameters.Add("oauth_nonce", oauthnonce)
basestringParameters.Add("oauth_signature_method", oauthsignaturemethod)
basestringParameters.Add("oauth_timestamp", oauthtimestamp)
basestringParameters.Add("oauth_token", oauthtoken)
Dim baseString As StringBuilder = New StringBuilder()
baseString.Append("GET" & "&")
baseString.Append(EncodeCharacters(Uri.EscapeDataString(url.Split("?"c)(0)) & "&"))
For Each entry As KeyValuePair(Of String, String) In basestringParameters
baseString.Append(EncodeCharacters(Uri.EscapeDataString(entry.Key & "=" + entry.Value & "&")))
Next
Dim finalBaseString As String = baseString.ToString().Substring(0, baseString.Length - 3)
Dim signingKey As String = EncodeCharacters(Uri.EscapeDataString(oauthconsumersecret)) & "&" + EncodeCharacters(Uri.EscapeDataString(oauthtokensecret))
Dim hasher As HMACSHA1 = New HMACSHA1(New ASCIIEncoding().GetBytes(signingKey))
Dim oauthsignature As String = Convert.ToBase64String(hasher.ComputeHash(New ASCIIEncoding().GetBytes(finalBaseString)))
ServicePointManager.Expect100Continue = False
Dim wRequest As HttpWebRequest = CType(WebRequest.Create(url), HttpWebRequest)
Dim authorizationHeaderParams As StringBuilder = New StringBuilder()
authorizationHeaderParams.Append("OAuth ")
authorizationHeaderParams.Append("oauth_nonce=" & """" + Uri.EscapeDataString(oauthnonce) & """,")
authorizationHeaderParams.Append("oauth_signature_method=" & """" + Uri.EscapeDataString(oauthsignaturemethod) & """,")
authorizationHeaderParams.Append("oauth_timestamp=" & """" + Uri.EscapeDataString(oauthtimestamp) & """,")
authorizationHeaderParams.Append("oauth_consumer_key=" & """" + Uri.EscapeDataString(oauthconsumerkey) & """,")
If Not String.IsNullOrEmpty(oauthtoken) Then authorizationHeaderParams.Append("oauth_token=" & """" + Uri.EscapeDataString(oauthtoken) & """,")
authorizationHeaderParams.Append("oauth_signature=" & """" + Uri.EscapeDataString(oauthsignature) & """,")
authorizationHeaderParams.Append("oauth_version=" & """" + Uri.EscapeDataString(oauthversion) & """")
wRequest.Headers.Add("Authorization", authorizationHeaderParams.ToString)
wRequest.Method = "GET"
wRequest.ContentType = "application/json"
wRequest.Accept = "application/json"
Try
Dim wResponse As WebResponse = wRequest.GetResponse()
Dim dataStream As Stream = wResponse.GetResponseStream()
Dim reader As StreamReader = New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
If responseFromServer = Nothing Then
TextBox1.Text = "No response from server"
Else
Dim json As String = responseFromServer
Dim ser As JObject = JObject.Parse(json)
Dim data As List(Of JToken) = ser.Children().ToList
Dim output As String = ""
Dim successReq As Boolean = False
Dim avDom As String = ""
For Each item As JProperty In data
item.CreateReader()
output += "|-" & item.Name.ToString & " : " & item.Value.ToString & "-"
output += Environment.NewLine
Next
TextBox1.Text = output
End If
Catch ex As Exception
TextBox1.Text = ex.Message.ToString
End Try
Private Function EncodeCharacters(ByVal data As String) As String
If data.Contains("!") Then data = data.Replace("!", "%21")
If data.Contains("'") Then data = data.Replace("'", "%27")
If data.Contains("(") Then data = data.Replace("(", "%28")
If data.Contains(")") Then data = data.Replace(")", "%29")
If data.Contains("*") Then data = data.Replace("*", "%2A")
If data.Contains(",") Then data = data.Replace(",", "%2C")
Return data
End Function
This example is working

How to get file's path created by this code?

I'm using this code to save files in my app
Dim filePath = String.Format("image{0:yyyyMMddHHmmss}.png", DateTime.Now)
PictureBox1.Image.Save(IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), (filePath)))
So now I have a textbox1 and I want to show the path of last saved image in it
how?
Regards,,,,
What I've done in the past is generate the path in one step and then use the generated variable to do the saving and to display.
So instead of:
Dim filePath = String.Format("image{0:yyyyMMddHHmmss}.png", DateTime.Now)
PictureBox1.Image.Save(IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), (filePath)))
Try:
'Generate the Path
Dim path As String = IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), String.Format("image{0:yyyyMMddHHmmss}.png", DateTime.Now))
'Save using the generated path
PictureBox1.Image.Save(path)
'Display the path
textbox1.Text = path
Thanks all I've done it successfully `
Dim filename As String = String.Format("image{0:yyyyMMddHHmmss}.png", DateTime.Now)
Dim filePath1 = (IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), (filename)))
Dim filePath2 = (IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), ("RMSS")))
If IO.Directory.Exists(IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), (" RMSS"))) = True Then
TextBox1.Text = filePath1
TextBox2.Text = filePath2 & "\" & filename
PictureBox1.Image.Save(filePath1)
My.Computer.FileSystem.MoveFile(TextBox1.Text, TextBox2.Text, True)
Else
TextBox1.Text = filePath1
TextBox2.Text = filePath2 & "\" & filename
PictureBox1.Image.Save(filePath1)
My.Computer.FileSystem.MoveFile(TextBox1.Text, TextBox2.Text, True)
End If

error deleting files after I send an email using VB Studio

Below is the email code I am using to send an email with attached document, but when I try to delete the files it is showing that the files are in use. Any help will be appreciated.
Sub email()
Dim Smtp_Server As New SmtpClient
Dim e_mail As New MailMessage()
Dim body As String
Dim address As String
Dim address2 As String
Dim address3 As String
Dim fileReader As System.IO.StreamReader
fileReader = My.Computer.FileSystem.OpenTextFileReader("C:\VB Test\location.txt")
Dim Pathstore As String
Pathstore = fileReader.ReadLine()
'email address
Dim lines() As String = System.IO.File.ReadAllLines("C:\VB Test\stores.txt")
For Each line As String In Filter(lines, Pathstore)
Dim fields() As String = line.Split(",")
address = fields(4)
address2 = fields(2)
address3 = fields(6)
Next
Dim fileReader2 As System.IO.StreamReader
fileReader2 = My.Computer.FileSystem.OpenTextFileReader("C:\VB Test\rmmsiul.dll")
Dim Pathcode As String
Pathcode = fileReader2.ReadLine()
fileReader2.Close()
body = "Here are the manual reciepts I created today." + vbNewLine + vbNewLine + vbNewLine & "Thank you," + vbNewLine + Pathstore
Smtp_Server.UseDefaultCredentials = False
Smtp_Server.Credentials = New Net.NetworkCredential("Do-Not-Reply#suncommobile.com", Pathcode)
Smtp_Server.Port = 587
Smtp_Server.EnableSsl = True
Smtp_Server.Host = "smtp.office365.com"
e_mail = New MailMessage()
e_mail.From = New MailAddress("Do-Not-Reply#suncommobile.com")
e_mail.CC.Add(address)
e_mail.CC.Add(address2)
e_mail.CC.Add(address3)
e_mail.Subject = Pathstore + " Manual reciepts"
e_mail.IsBodyHtml = False
e_mail.Body = body
Dim filepath As String
For Each filepath In Directory.GetFiles("C:\VB Test\Receipts")
Dim Attach As New Net.Mail.Attachment(filepath)
e_mail.Attachments.Add(Attach)
Kill(filepath)
Next
Smtp_Server.Send(e_mail)
MsgBox("E-mail Sent.")
Module1.filedelete()
End Sub
'changed part of the code to the following, but getting error when sending email.
For Each filepath As String In Directory.GetFiles("C:\VB Test\Receipts")
Using reader As New StreamReader(filepath)
Dim a As New Net.Mail.Attachment(reader.BaseStream, filepath)
e_mail.Attachments.Add(a)
End Using
Next
Smtp_Server.Send(e_mail)
Public Sub email()
Dim Pathstore As String = String.Empty
Dim Pathcode As String = String.Empty
With New StreamReader("C:\VB Test\location.txt")
Pathstore = .ReadLine()
.Dispose()
End With
' Are you sure this is the correct file ?
With New StreamReader("C:\VB Test\rmmsiul.dll")
Pathcode = .ReadLine()
.Dispose()
End With
' Capture the list of Attachment Files here, then use it twice below
Dim Attachments() As String = Directory.GetFiles("C:\VB Test\Receipts")
Dim e_mail As New Net.Mail.MailMessage()
With e_mail
.From = New Net.Mail.MailAddress("Do-Not-Reply#suncommobile.com")
.Subject = String.Format("{0} Manual reciepts", Pathstore)
.Body = String.Format("Here are the manual reciepts I created today.{0}{0}{0}Thank you,{0}{1}", Environment.NewLine, Pathstore)
' Since I don't know what Filter() returns, this is best guess to reproduce the same outcome
For Each line As String In Filter(File.ReadAllLines("C:\VB Test\stores.txt"), Pathstore)
Dim fields() As String = line.Split(",")
.CC.Clear()
.CC.Add(fields(4))
.CC.Add(fields(2))
.CC.Add(fields(6))
Next
For Each filepath In Attachments
.Attachments.Add(New Net.Mail.Attachment(filepath))
Next
End With
With New Net.Mail.SmtpClient
.Host = "smtp.office365.com"
.Credentials = New Net.NetworkCredential("Do-Not-Reply#suncommobile.com", Pathcode)
.Port = 587
.EnableSsl = True
.Send(e_mail)
End With
' Dispose the MailMessage to release the holds on the Attachment Files
e_mail.Dispose()
' Delete the Attachment Files
For Each filepath In Attachments
File.Delete(filepath)
Next
MsgBox("E-mail Sent.")
End Sub

Poll a directory looking for files with a certain extension

I'm writing a script to look in a directory, read the file name and use a part of the file name to run a SQL query to amend a DB, then copy the files to a new location and delete the original.
Once this is done it sends an email confirmation to a predefined email address.
I have the majority in place but am not able to Poll a Dir and process all files that may be there. Im new to this VB.net stuff and to get the other stuff working iv just named it at the beginning.
Any help would be greatly appreciated.
Dim fileName As String = "C:\temp\Input\VBTEST1.success"
Dim pathname As String = "C:\temp\Input\"
Dim result As String
Dim sourceDir As String = "C:\temp\Input\"
Dim processedDir As String = "C:\temp\Input\Processed\"
Dim fList As String() = Directory.GetFiles(sourceDir, "*.success")
Dim sqlCommand As SqlCommand
Public Sub Main()
result = Path.GetFileName(fileName)
Console.WriteLine("GetFileName('{0}') returns '{1}'", fileName, result)
Dim betacell As String = result
betacell = (result.Remove(7, 8))
Dim connection As New SqlConnection(My.Settings.connectionString)
connection.Open()
Dim updateTransaction As SqlTransaction = connection.BeginTransaction()
Dim sqlQ As String = "UPDATE " & My.Settings.JobTb & " SET Status = '10' WHERE JobNumber ='" & betacell & "'"
sqlCommand = New SqlCommand(sqlQ, connection, updateTransaction)
sqlCommand.ExecuteNonQuery()
updateTransaction.Commit()
connection.Close()
SendEmail(My.Settings.emailUsers, "EMAIL TEXT")
Call MoveFiles()
End Sub
I'm all chuffed now as iv also managed to make it look for all files with a .success extension. Now it processes all files and not the one named in the code.
Module Module1
Dim sourceDir As String = My.Settings.watchPath
Dim processedDir As String = My.Settings.processedPath
Private loggerName As String = "EmailReleases"
Public Sub log(ex As Exception)
Console.WriteLine("Error: " & ex.ToString)
End Sub
Public Sub log(ByVal s As String)
Console.WriteLine(DateTime.Now.ToString & " [" & loggerName & "] " & s)
End Sub
Public Sub Main()
Dim inputFiles As String() = Directory.GetFiles(sourceDir, "*.success")
log("Starting processing of .success files in '" & sourceDir & "' ... ")
If (inputFiles.Length > 0) Then
Dim connection As New SqlConnection(My.Settings.connectionString)
connection.Open()
For Each fileName As String In inputFiles
Dim sqlCommand As SqlCommand
Dim fFile As New FileInfo(fileName)
log(" Processing " & fFile.Name)
Dim betacell As String = fFile.Name.Substring(0, fFile.Name.Length - 8)
'Update Status on Database with the use of the Betacell
Dim updateTransaction As SqlTransaction = connection.BeginTransaction()
Dim sqlQ As String = "UPDATE " & My.Settings.JobTb & " SET Status = '10' WHERE JobNumber ='" & betacell & "'"
sqlCommand = New SqlCommand(sqlQ, connection, updateTransaction)
Dim result = sqlCommand.ExecuteNonQuery()
'Email COnfirmation
SendEmail(My.Settings.emailUsers, "EMAIL TEXT")
If (result > 0) Then
'Move the file
fFile.MoveTo(processedDir & fFile.Name)
updateTransaction.Commit() ' make sure to commit only in case moving the file is OK
Else
log("ERROR - Betacell '" & betacell & "' not found in database!")
updateTransaction.Rollback()
End If
Rather than polling a folder (i.e. checking every n seconds whether it has new files) it's much more efficient to have the operating system notify you of changes in that folder. You can do this by creating a FileSystemWatcher. There is an example on MSDN.
However, if you did want to poll a folder, it's actually nice and easy - just wrap the following code in a Timer. Please note I normally code in C#, so apologies if the syntax is not 100%...
Imports System.IO
....
For Each file as String in Directory.GetFiles("C:\SomeFolder")
DoSomethingWithFile (file)
Next

Load Image files from folder

I have a checked list box and a thumbnail area to display them where I am trying to load only images from a specific folder and need to display in thumbnails area but the problem is there is a thumbs.db file which is also being added to the checked list box which I don't need it.
So how do I actually load only the image files without the thumbs.db file.
Here is my code:
Private Sub LoadProjectToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles LoadProjectToolStripMenuItem.Click
Using ofdlg As New Windows.Forms.OpenFileDialog
ofdlg.DefaultExt = "trk"
ofdlg.Filter = "Project|*.trk"
ofdlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
If ofdlg.ShowDialog = Windows.Forms.DialogResult.OK Then
Dim SaveData As New gCanvasData
Using objStreamReader As New StreamReader(ofdlg.FileName)
Dim x As New XmlSerializer(GetType(gCanvasData))
SaveData = CType(x.Deserialize(objStreamReader), gCanvasData)
objStreamReader.Close()
End Using
With SaveData
'gTSSizer_gAZoom.Value = 100
GCanvas1.ImageXYReset()
GCanvas1.Image = .Image
GCanvas1.gAnnotates = .gAnnotates
GCanvas1.RebuildAll()
GCanvas1.AssembleBitmap()
End With
Dim fullpath As String
fullpath = Application.StartupPath + "\" & System.IO.Path.GetFileNameWithoutExtension(ofdlg.FileName) + "\"
For Each fi As FileInfo In New DirectoryInfo(fullpath).GetFiles
CheckedListBox1.Items.Add(Application.StartupPath + "\" & System.IO.Path.GetFullPath(ofdlg.FileName))
For i As Integer = 0 To CheckedListBox1.Items.Count - 1
CheckedListBox1.SetItemChecked(i, True)
ThumbControl1.AddFolder(fullpath, True)
Next i
Next
End If
End Using
End Sub
Either filter it inside of the For Each Loop:
For Each fi As FileInfo In New DirectoryInfo(fullpath).GetFiles
If Not {".jpg", ".png", ".bmp"}.Contains(fi.Extension) Then Continue For
' ...
Next
or do it in the GetFiles:
DirectoryInfo(fullpath).GetFiles(".jpg")
Found the solution at last:
Dim fullpath As String
fullpath = Application.StartupPath & "\" & System.IO.Path.GetFileNameWithoutExtension(ofdlg.FileName) + "\"
Dim FileDirectory As New IO.DirectoryInfo(fullpath)
Dim FileJpg As IO.FileInfo() = FileDirectory.GetFiles("*.jpg")
Dim FileGif As IO.FileInfo() = FileDirectory.GetFiles("*.gif")
Dim FileBmp As IO.FileInfo() = FileDirectory.GetFiles("*.bmp")
For Each File As IO.FileInfo In FileJpg
CheckedListBox1.Items.Add(File.FullName)
Dim str As String
str = Directory.GetCurrentDirectory() & "\" & "Backup\"
Next
For Each File As IO.FileInfo In FileGif
CheckedListBox1.Items.Add(File.FullName)
Dim str As String
str = Directory.GetCurrentDirectory() & "\" & "Backup\"
Next
For Each File As IO.FileInfo In FileBmp
CheckedListBox1.Items.Add(File.FullName)
Dim str As String
str = Directory.GetCurrentDirectory() & "\" & "Backup\"
Next
For i As Integer = 0 To CheckedListBox1.Items.Count - 1
CheckedListBox1.SetItemChecked(i, True)
Next i
Change DirectoryInfo(fullpath).GetFiles to DirectoryInfo(fullpath).EnumerateFiles() And add a search pattern for the image file extensions you want. http://msdn.microsoft.com/en-us/library/dd383574.aspx