Listview and close form not delete directory - vb.net

My listview codes:
Const IMAGE_DIRECTORY As String = "outfile"
Dim files As String() = Directory.GetFiles(IMAGE_DIRECTORY)
Dim max_length, i As Integer
Dim fname As String
Dim pname As String
Dim myImage As Image
'Set the ColorDepth and ImageSize properties of imageList1.
ImageList1.ColorDepth = ColorDepth.Depth32Bit
ImageList1.ImageSize = New System.Drawing.Size(106, 150)
max_length = files.Length - 1
'Add images to imageList1.
For i = 0 To max_length
pname = Path.GetFullPath(files(i))
myImage = Image.FromFile(pname)
ImageList1.Images.Add(myImage)
myImage = Nothing
Next
pname = Nothing
'ListView1.View = View.LargeIcon
ListView1.LargeImageList = ImageList1
For i = 0 To files.Length - 1
fname = Path.GetFileName(files(i))
Dim listViewItem1 As ListViewItem = New ListViewItem(fname, i)
'Add listViewItem1 and listViewItem2.
ListView1.Items.AddRange(New ListViewItem() {listViewItem1})
listViewItem1 = Nothing
Next
'Me.Controls.AddRange(New Control() {listView1})
ListView1.Items(0).Selected = True
ListView1.Select()
Exit command button and remove files error now:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Me.PictureBox2.Image.Dispose()
Me.ImageList1.Dispose()
Me.PictureBox2.Image.Dispose()
Me.Dispose()
Me.Close()
End Sub
Exit form and remove directory outfile error :
System.IO.IOException was unhandled
   HRESULT = -2147024864
   Message = The process is being used by another process 'Seite0.Jpg' can not access the file.
   Source = mscorlib
What is the code problem ?

Related

Get percentage of files copied from a list

I have an app that copies files in a list to a new directory. I'm trying to get the progress bar to work but my formula results with a System.OverflowException: Arithmetic operation resulted in an over flow. I've looked at other examples using file copying but they are centered on using the source folder divided by destination folder. Mines a little bit different because I'm using files in a list.
Thank you for the help.
Code
Dim progress = fileCount * 100 / fileList.Count()
BackgroundWorker1.ReportProgress(progress)
Code for getting file Count
Dim FILE_NAME As String
FILE_NAME = txtFileName.Text
Dim fileNames = System.IO.File.ReadAllLines(FILE_NAME)
fCount = 0
For i = 0 To fileNames.Count() - 1
Dim fileName = fileNames(i)
sFileToFind = location & "\" & fileName & "*.*"
Dim paths = IO.Directory.GetFiles(location, fileName, IO.SearchOption.AllDirectories)
If Not paths.Any() Then
System.IO.File.AppendAllText(orphanedFiles, fileName & vbNewLine)
Else
For Each pathAndFileName As String In paths
If System.IO.File.Exists(pathAndFileName) = True Then
sRegLast = pathAndFileName.Substring(pathAndFileName.LastIndexOf("\") + 1)
Dim toFileLoc = System.IO.Path.Combine(createXMLFldr, sRegLast)
Dim moveToFolder = System.IO.Path.Combine(MoveLocation, "XML files", sRegLast)
'if toFileLoc = XML file exists move it into the XML files folder
If System.IO.File.Exists(toFileLoc) = False Then
System.IO.File.Copy(pathAndFileName, moveToFolder)
System.IO.File.AppendAllText(ListofFiles, sRegLast & vbNewLine)
fCount = fCount + 1
XMLFilename = (sRegLast) + vbCrLf
End If
End If
Next
End If
Dim srcCount = paths.Count()
If (paths.Count() = 0) Then
srcCount = 1
End If
Dim progress = CType(fCount * 100 / srcCount, Integer)
BackgroundWorker1.ReportProgress(progress)
Next
This for BackGroundWorker, I hope will this can resolve the trouble of the next call to update progress bar:
'This button1_click event to begin or stop async of backGrounedWorker
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
BackgroundWorker1.WorkerReportsProgress = True
BackgroundWorker1.WorkerSupportsCancellation = True
BackgroundWorker1.CancelAsync()
Try
BackgroundWorker1.RunWorkerAsync()
Catch ex As Exception
End Try
End Sub
'Here your backGroundProcess
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim FILE_NAME As String
FILE_NAME = txtFileName.Text 'can be changed
Dim fileNames = System.IO.File.ReadAllLines(FILE_NAME)
Dim Location As String = "C:\MyData\Folder1" 'can be changed
Dim moveToFolder As String = "C:\MyData\Folder2" 'can be changed
Dim fCount As Integer = 0
For Each fileName In fileNames
Dim paths = IO.Directory.GetFiles(Location, fileName,
IO.SearchOption.AllDirectories)
If paths.Count > 0 Then
Try
System.IO.File.Copy(paths(0), moveToFolder & "\" & fileName, True)
Catch ex As Exception
Debug.Print(ex.Message)
End Try
End If
For a = 1 To 100
Debug.Print(a.ToString)
Next
'If any request pending process will be stop (when Button1_click happen while process running (BackGroundWorker in Action))
If BackgroundWorker1.CancellationPending = True Then Exit For
fCount += 1
Dim Progress As Integer = Convert.ToInt32(fCount * 100 / fileNames.Count)
BackgroundWorker1.ReportProgress(progress)
Next
End Sub
'This will show you the progress in your progress bar
Private Sub bw1_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
Me.ProgressBar1.Value = e.ProgressPercentage
End Sub
'Your Process Have Been Complete Here
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
MessageBox.Show("Finish")
End Sub
This last modification from me:
ListBox1.Items.Clear()
Dim FILE_NAME As String
FILE_NAME = "c:\YourFolder\YourFile.txt" 'can be changed
Dim fileNames = System.IO.File.ReadAllLines(FILE_NAME)
For Each MyFile In fileNames
ListBox1.Items.Add(MyFile)
Next
Dim Location As String = "C:\YourFolder1" 'can be changed
Dim moveToFolder As String = "C:\YourFolder2" 'can be changed
Dim fCount As Integer = 0
For Each fileName In fileNames
Dim paths = IO.Directory.GetFiles(Location, fileName,
IO.SearchOption.AllDirectories)
If paths.Count > 0 Then
Try
System.IO.File.Copy(paths(0), fileName)
Catch ex As Exception
End Try
End If
fCount += 1
Dim progress As Integer = Convert.ToInt32(fCount * 100 / fileNames.Count)
Next

hide folder name in tree list

how do i hide specific name folder within the treelist ? i have tree list like this
and i want to hide folder name New folder and pdf. i make this from Load Data Dir. i have tweak a bit in the code like this by putting if
Dim rootfolder As String = "C:\\FFOutput"
Private Sub TreeList1_VirtualTreeGetCellValue(ByVal sender As Object, ByVal e As DevExpress.XtraTreeList.VirtualTreeGetCellValueInfo) Handles TreeList1.VirtualTreeGetCellValue
Dim di As New DirectoryInfo(CStr(e.Node))
If di.Name <> "New folder" Then
If e.Column Is TreeListColumn1 Then
e.CellData = di.Name
End If
If e.Column Is TreeListColumn2 Then
e.CellData = e.Node.ToString
End If
If e.Column Is TreeListColumn3 Then
If IsFile(di) Then
e.CellData = New FileInfo(CStr(e.Node)).Extension
Else
e.CellData = Nothing
End If
End If
End If
End Sub
Private Sub TreeList1_VirtualTreeGetChildNodes(ByVal sender As Object,
ByVal e As DevExpress.XtraTreeList.VirtualTreeGetChildNodesInfo) _
Handles TreeList1.VirtualTreeGetChildNodes
If loadDrives = False Then
Dim root As String() = Directory.GetDirectories(rootfolder)
e.Children = root
loadDrives = True
Else
Try
Dim di As New DirectoryInfo(CStr(e.Node))
If di.Name <> "New folder" Then
Dim path As String = CStr(e.Node)
If Directory.Exists(path) Then
Dim dirs As String() = Directory.GetDirectories(path)
Dim files As String() = Directory.GetFiles(path)
Dim arr(dirs.Length + files.Length) As String
dirs.CopyTo(arr, 0)
files.CopyTo(arr, dirs.Length)
e.Children = arr
Else
e.Children = New Object() {}
End If
End If
Catch
End Try
End If
End Sub
and it become like this

Attaching a screenshot to new email outlook image with vb net

been looking for a bit of code to take a screenshot and attach the screenshot to new email. I'll post what I have. It work 99%, just can't for the life of me figure out why it isn't attaching to the email.
It does everything but attach the new screenshot to the email. Is this possible?
Private Sub testStripMenuItem_Click(sender As Object, e As EventArgs) Handles testStripMenuItem.Click
Dim maxHeight As Integer = 0
Dim maxWidth As Integer = 0
For Each scr As Screen In Screen.AllScreens
maxWidth += scr.Bounds.Width
If scr.Bounds.Height > maxHeight Then maxHeight = scr.Bounds.Height
Next
Dim AllScreensCapture As New Bitmap(maxWidth, maxHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb)
Dim screenGrab As Bitmap
Dim screenSize As Size
Dim g As Graphics
Dim g2 As Graphics = Graphics.FromImage(AllScreensCapture)
Dim a As New Point(0, 0)
For Each scr As Screen In Screen.AllScreens
screenSize = New Size(scr.Bounds.Width, scr.Bounds.Height)
screenGrab = New Bitmap(scr.Bounds.Width, scr.Bounds.Height)
g = Graphics.FromImage(screenGrab)
g.CopyFromScreen(a, New Point(0, 0), screenSize)
g2.DrawImage(screenGrab, a)
a.X += scr.Bounds.Width
Next
Dim Screenshot = "C:\img.png"
If System.IO.File.Exists(Screenshot) Then
System.IO.File.Delete(Screenshot)
End If
AllScreensCapture.Save(Screenshot, System.Drawing.Imaging.ImageFormat.Jpeg)
'Email Code
Dim strUserDomain As String
Dim strCompName As String
strUserDomain = Environ$("UserDomain")
strCompName = Environ$("ComputerName")
Dim theStringBuilder As New StringBuilder()
theStringBuilder.Append("mailto:email#gmail.com.au")
theStringBuilder.Append("&subject=From Domain: " & strUserDomain & ". Computer Name: " & strCompName)
theStringBuilder.Append("&attach=" & Screenshot)
Process.Start(theStringBuilder.ToString())
End Sub
Alternative to sending through an installed mail client...
' Some of these may come from the form or user settings or wherever
Private Const MailSenderEmail As String = ""
Private Const MailSenderName As String = ""
Private Const MailRecipient As String = ""
Private Const MailSubject As String = ""
Private Const MailBody As String = ""
Private Const MailHost As String = ""
Private Const MailPort As String = ""
Private Const MailUser As String = ""
Private Const MailPass As String = ""
Private Const MailEnableSsl As Boolean = False
Private Sub testStripMenuItem_Click(sender As Object, e As EventArgs) Handles testStripMenuItem.Click
'
' Your code to capture the screen
'
Dim Screenshot = "C:\img.png"
If System.IO.File.Exists(Screenshot) Then
System.IO.File.Delete(Screenshot)
End If
AllScreensCapture.Save(Screenshot, System.Drawing.Imaging.ImageFormat.Jpeg)
' Send the email with Screenshot attached
Using MailMessage As New Net.Mail.MailMessage
With MailMessage
.From = New Net.Mail.MailAddress(MailSenderEmail, MailSenderName)
.To.Add(MailRecipient)
.Subject = MailSubject
.Body = MailBody
.Attachments.Add(New Net.Mail.Attachment(Screenshot))
End With
With New Net.Mail.SmtpClient
.Host = MailHost
.Port = MailPort
.EnableSsl = MailEnableSsl
Select Case True
Case String.IsNullOrWhiteSpace(MailUser)
Case String.IsNullOrWhiteSpace(MailPass)
Case Else
.Credentials = New Net.NetworkCredential(MailUser, MailPass)
End Select
.Send(MailMessage)
End With
End Using
End Sub

Datagridview strange display error on init

upon initialization of my UI i get the following very strange behavior regarding to the drawing of the datagridview:
Basically, expect the first row header and the column headers (which i did not include in the pic) it looks like the DGV prints what is on the Screen "behind" his application.
What the hell is this and does anyone know a way to fix it?
Code of Container:
Public Class DGVControl
Dim dt As DataTable
Public Sub init()
dt = New DataTable
Dim arr(ldfAttributes.Count - 1) As String
Dim cms As New ContextMenuStrip
Dim i As Integer = 0
For Each att As String In Attributes.Keys
Dim cmsitem As New ToolStripMenuItem
dt.Columns.Add(att, GetType(String))
cmsitem.Name = att
cmsitem.Text = att
cmsitem.Owner = cms
cmsitem.CheckOnClick = True
cmsitem.Checked = my.Settings.shownColumns.Contains(att)
AddHandler cmsitem.CheckedChanged, AddressOf showOrHideColumn
cms.Items.Add(cmsitem)
arr(i) = "No Data"
i += 1
Next
For i = 1 To my.settings.anzEntries
dt.Rows.Add(arr)
Next
MainDGV.DataSource = dt
MainDGV.ContextMenuStrip = cms
For Each attName as String In Attributes.key
showOrHideColumn(cms.Items(attName), New EventArgs())
Next
MainDGV.RowHeadersWidth = 90
MainDGV.RowTemplate.Height = 40
MainDGV.RowHeadersDefaultCellStyle.BackColor = Color.White
MainDGV.RowHeadersDefaultCellStyle.Font = New Font(MainDGV.ColumnHeadersDefaultCellStyle.Font, FontStyle.Bold)
MainDGV.ColumnHeadersDefaultCellStyle.BackColor = Color.White
MainDGV.ColumnHeadersDefaultCellStyle.Font = New Font(MainDGV.ColumnHeadersDefaultCellStyle.Font, FontStyle.Bold)
MainDGV.BackgroundColor = Color.White
End Sub
Private Sub showOrHideColumn(sender As Object, e As EventArgs)
Dim cmsitem As ToolStripMenuItem = CType(sender, ToolStripMenuItem)
MainDGV.Columns(cmsitem.Name).Visible = cmsitem.Checked
End Sub
'taken from: http://stackoverflow.com/questions/710064/adding-text-to-datagridview-row-header
Private Sub nameRowHeaders(sender As Object, e As EventArgs) Handles MainDGV.DataBindingComplete
Dim dgv As DataGridView = CType(sender, DataGridView)
For i As Integer = 0 To dgv.RowCount - 1
dgv.Rows(i).HeaderCell.Value = ("Entry " &(i+1).toString())
Next
End Sub
End Class
EDIT:
As soon as you once select a row, all cells will be displayed in the right way until you restart the application

VB.NET File Explorer

I'm making a File Explorer in VB.NET. Everything is going fine except one thing. When you click the dynamically created label to "open" a folder, I need to get the value of the label (so I can set a variable to it.) I can't get the value because the label was dynamically create. Therefore the object doesn't exist. Here's my code:
Imports System.IO
Public Class Form1
Dim Path As String
Dim FolderCount = 0
Dim FolderWidth = 128
Dim FolderHeight = 128
Dim WidthAndPadding = FolderWidth + 10
Dim HeightAndPadding = FolderHeight + 10
Dim FolderTitle As String
Dim CombinedWidth
Dim FolderRows = 0
Dim OnNewLine = False
Dim FolderTop = 0
Dim FolderLeft = 0
Dim FullPath
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.AutoScroll = True
Path = "C:\Program Files\"
For Each Dir As String In Directory.GetDirectories(Path)
CreateFolders(Dir)
Next
End Sub
Public Sub CreateFolders(ByVal StrDirectory)
FolderTitle = StrDirectory.Substring(Path.Length)
Dim Folder As New Label
FolderLeft = WidthAndPadding * FolderCount
Folder.Left = FolderLeft
Folder.Top = FolderTop
Folder.Width = FolderWidth
Folder.Height = FolderHeight
Folder.Image = My.Resources.Folder
Folder.TextAlign = ContentAlignment.BottomCenter
If FolderTitle.Length > 15 Then
FolderTitle = FolderTitle.Substring(0, 15) + "..."
End If
Folder.Text = FolderTitle
Folder.Font = New Font("Arial", 9.5)
FolderCount += 1
CombinedWidth = FolderCount * WidthAndPadding
If CombinedWidth >= Me.Width Then
OnNewLine = False
If OnNewLine = False Then
FolderRows = FolderRows + 1
FolderCount = 0
CombinedWidth = 0
Folder.Left = FolderCount * FolderWidth
FolderTop = FolderRows * FolderHeight
Folder.Top = FolderTop
OnNewLine = True
'FolderCount += 1
End If
End If
Me.Controls.Add(Folder)
AddHandler Folder.DoubleClick, AddressOf Folder_DoubleClick
FullPath = Path + FolderTitle
End Sub
Private Sub Folder_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs)
'MsgBox(Folder.Text)
End Sub
End Class
The event handler's sender parameter contains the label that generated the event.
You can cast it back to Label by writing CType(sender, Label).