Displaying Application Icons (and names) in ListView Object - vb.net

I,
I'm creating a VB Form with a ListView object containing Images of Excel, Word or Pdf Icons, with a link to the displayed document (to be made)
When compilating, the names of the documents are displayed in the listView but not the icons. Do you know what is missing in my code?
As far as I understand, the "ExtractAssociatedIcon" method needs the full path to the file, but it seems that no Icon is collected here.
Thanks
Imports System
Imports System.IO
Imports System.Drawing
[...]
Dim dirInfo As DirectoryInfo
Dim fileInfo As FileInfo
Dim exePath As String
Dim exeIcon As Drawing.Icon
dirInfo = New DirectoryInfo("G:\XXX\XXX\XXX\XXX\XXX")
'We use this For...Each to iterate over the collection of files in the folder
For Each fileInfo In dirInfo.GetFiles
'We can only find associated exes by extension, so don't show any files that have no extension
If fileInfo.Extension = String.Empty Then
Else
'Use the function to get the path to the executable for the file
exePath = fileInfo.FullName
'Use ExtractAssociatedIcon to get an icon from the path
exeIcon = Drawing.Icon.ExtractAssociatedIcon(exePath)
'Add the icon if we haven't got it already, with the executable path as the key
If ImageList1.Images.ContainsKey(exePath) Then
Else
ImageList1.Images.Add(exePath, exeIcon)
End If
'Add the file to the ListView, with the executable path as the key to the ImageList's image
ListView1.View = View.LargeIcon
ListView1.Items.Add(fileInfo.Name, exePath)
End If
Next

1) You need to set the SmallImageList and/or the LargeImageList property of the ListView:
ListView1.LargeImageList = ImageList1
ListView1.SmallImageList = ImageList1
2) Put this at the top of your code. (Not in the For Each loop)
ListView1.View = View.LargeIcon
3) Also, be sure that you don't add an empty icon, nor sets an invalid image key:
If (ImageList1.Images.ContainsKey(exePath)) Then
ListView1.Items.Add(fileInfo.Name, exePath)
ElseIf (Not exeIcon Is Nothing) Then
ImageList1.Images.Add(exePath, exeIcon)
ListView1.Items.Add(fileInfo.Name, exePath)
Else
ListView1.Items.Add(fileInfo.Name)
End If
Example
The following code is tested and works fine:
ListView1.LargeImageList = ImageList1
ListView1.SmallImageList = ImageList1
ListView1.View = View.LargeIcon
Dim dirInfo As DirectoryInfo
Dim fileInfo As FileInfo
Dim exeIcon As System.Drawing.Icon
dirInfo = New DirectoryInfo("...")
For Each fileInfo In dirInfo.GetFiles
If (Not String.IsNullOrEmpty(fileInfo.Extension)) Then
exeIcon = System.Drawing.Icon.ExtractAssociatedIcon(fileInfo.FullName)
If (ImageList1.Images.ContainsKey(fileInfo.FullName)) Then
ListView1.Items.Add(fileInfo.Name, fileInfo.FullName)
ElseIf (Not exeIcon Is Nothing) Then
ImageList1.Images.Add(fileInfo.FullName, exeIcon)
ListView1.Items.Add(fileInfo.Name, fileInfo.FullName)
Else
ListView1.Items.Add(fileInfo.Name)
End If
End If
Next

Related

How to display a single Windows Explorer folder (that cannot be navigated away from) within a userform?

I would like to have a box within the userform display the contents of a single folder.
I would like the folder to display icons similar to how Windows Explorer does, and I would also like users to be able to drag icons from other windows into it (just like a real explorer window).
I decided to use a listview, and this will populate it with a bunch of lines of text for each file, but clicking on them does nothing and I cannot drag anything in. Also they don't have icons.
Any ideas?
Dim fileEntries As String() = Directory.GetFiles("C:\Windows\")
For Each fileName As String In fileEntries
ListView1.Items.Add(fileName)
Next
This MSDN article describes exactly how to do this. it even gets the icons, as you requested! It also uses a ListView, too! Enjoy!
As Jeremy said, you will still need to hook up event, if you want it to respond to click (or drag) events.
Private listView1 As ListView
Private imageList1 As ImageList
Public Sub ExtractAssociatedIconEx()
' Initialize the ListView, ImageList and Form.
listView1 = New ListView()
imageList1 = New ImageList()
listView1.Location = New Point(37, 12)
listView1.Size = New Size(161, 242)
listView1.SmallImageList = imageList1
listView1.View = View.SmallIcon
Me.ClientSize = New System.Drawing.Size(292, 266)
Me.Controls.Add(Me.listView1)
Me.Text = "Form1"
' Get the c:\ directory.
Dim dir As New System.IO.DirectoryInfo("c:\")
Dim item As ListViewItem
listView1.BeginUpdate()
Dim file As System.IO.FileInfo
For Each file In dir.GetFiles()
' Set a default icon for the file.
Dim iconForFile As Icon = SystemIcons.WinLogo
item = New ListViewItem(file.Name, 1)
' Check to see if the image collection contains an image
' for this extension, using the extension as a key.
If Not (imageList1.Images.ContainsKey(file.Extension)) Then
' If not, add the image to the image list.
iconForFile = System.Drawing.Icon.ExtractAssociatedIcon(file.FullName)
imageList1.Images.Add(file.Extension, iconForFile)
End If
item.ImageKey = file.Extension
listView1.Items.Add(item)
Next file
listView1.EndUpdate()
End Sub

Upload and replace the same image file if it already exist

I have a picturebox named PB_Company_Logo and I have a button named btn_Save and within this button I have this function which saves the image in PB_Company_Logo to current_directory/images
Public Sub save_PB(PB_Name As PictureBox)
Dim filename As String = "company_logo.png"
Dim path As String = Directory.GetCurrentDirectory() & "\images"
Dim filename_path As String = System.IO.Path.Combine(path, filename)
If (Not System.IO.Directory.Exists(path)) Then
System.IO.Directory.CreateDirectory(path)
PB_Name.Image.Save(filename_path)
Else
PB_Name.Image.Save(filename_path)
End If
End Sub
The problem is, there are cases where the user will upload a new company_logo.png. I want the system to treat the uploading of new image as replacing the former company_logo.png.
I think the error in this line of code means that the file is currently in used (locked) and therefore cannot be replaced.
Else
PB_Name.Image.Save(filename_path)
End If
When you load a pictureBox control with an image file the ide (vs) puts a lock on the file. This happens when you set the image property of the pictureBox control to a file at design time.
You can use the FileStream object.
Example:
Dim fs As System.IO.FileStream
' Specify a valid picture file path on your computer.
fs = New System.IO.FileStream("C:\WINNT\Web\Wallpaper\Fly Away.jpg",
IO.FileMode.Open, IO.FileAccess.Read)
PictureBox1.Image = System.Drawing.Image.FromStream(fs)
fs.Close()
After you have done the workaround you can then use the System.IO.File.Exists(img) namespace to check wether or not a picture exists.
Example: This checks if the image passed through already exists and if it does then it will replace it.
Dim imageStr As String = "~/images/name.jpg"
If System.IO.File.Exists(imageStr) Then
Image1.ImageUrl = "~/images/name.jpg"
End If

How To Get Icons For Pictures Files in vb.net

I Tried To Get Icons Of files system and display it in my list Box
But i got an empty icon For Picture Files
This Is My Code:
Public Sub ExtractAssociatedIconEx()
' Initialize the ListView, ImageList and Form.
listView1 = New ListView()
imageList1 = New ImageList()
listView1.Location = New Point(37, 12)
listView1.Size = New Size(161, 242)
listView1.SmallImageList = imageList1
listView1.View = View.SmallIcon
Me.ClientSize = New System.Drawing.Size(292, 266)
Me.Controls.Add(Me.listView1)
Me.Text = "Form1"
' Get the c:\ directory.
Dim dir As New System.IO.DirectoryInfo(TextBox1.Text)
Dim item As ListViewItem
listView1.BeginUpdate()
Dim file As System.IO.FileInfo
For Each file In dir.GetFiles()
' Set a default icon for the file.
Dim iconForFile As Icon = SystemIcons.WinLogo
item = New ListViewItem(file.Name, 1)
' Check to see if the image collection contains an image
' for this extension, using the extension as a key.
If Not (imageList1.Images.ContainsKey(file.Extension)) Then
' If not, add the image to the image list.
iconForFile = System.Drawing.Icon.ExtractAssociatedIcon(file.FullName)
imageList1.Images.Add(file.Extension, iconForFile)
End If
item.ImageKey = file.Extension
listView1.Items.Add(item)
Next file
listView1.EndUpdate()
End Sub
How I Can Get Icons For picture Files ?
Thanks

VB.NET: GetFiles Method - "Access to the path 'G:\System Volume Information' is denied."

Here is my code,
Dim allFiles As FileInfo() =
tempDir.GetFiles("*.pdf", SearchOption.AllDirectories)
I've googled and found that I need to change the permissions of my app from
Project properties > View UAC Settings > and change level to level="requireAdministrator"
But its also not working. I found something about FileIOPermission class, but dont know how to implement it.
==> Detailed code.
Dim tempDir As New DirectoryInfo(path)
Dim FileDetails(4) As String
Dim iTem As ListViewItem
If (tempDir.Attributes <> FileAttributes.System) Then
Dim allFiles As FileInfo() = tempDir.GetFiles("*.pdf", SearchOption.AllDirectories)
Dim oneFIle As FileInfo
For Each oneFIle In allFiles
FileDetails(0) = oneFIle.Name()
FileDetails(1) = oneFIle.FullName()
FileDetails(2) = oneFIle.Length() / (1024 * 1024)
FileDetails(2) = FileDetails(2).Remove(5)
iTem = New ListViewItem(FileDetails)
ListView1.Items.Add(iTem)
Next
End If
Path is a string that contains the path required, in this case G:\
You won't find PDF files in this folder:
The System Volume Information folder is a hidden system folder that the System Restore tool uses to store its information and restore points. (MSDN)
So just ignore it.
Granted, GetFiles() does not allow you to ignore files/folders, so you'd have to PInvoke into FindFirstFile et al. to do searches effectively.
Ok, I think I solved the case, I just iterated each folder, checked their attributes and then added to the list.. I think it's working.. Plz check it a bit..
Dim tempDir As New DirectoryInfo(path)
Dim FileDetails(4) As String
Dim iTem As ListViewItem
Try
Dim allFiles As FileInfo() = Nothing
For Each Directory In tempDir.GetDirectories()
Try
If (Directory.Attributes <> FileAttributes.System) Then
allFiles = Directory.GetFiles("*.pdf", SearchOption.AllDirectories)
End If
Dim oneFIle As FileInfo
For Each oneFIle In allFiles
FileDetails(0) = oneFIle.Name()
FileDetails(1) = oneFIle.FullName()
FileDetails(2) = oneFIle.Length() / (1024 * 1024)
FileDetails(2) = FileDetails(2).Remove(5)
iTem = New ListViewItem(FileDetails)
ListView1.Items.Add(iTem)
Next
Catch ex As Exception
End Try
Next
Catch ex As UnauthorizedAccessException
End Try
System Volume Information Folder is a O/S protected folder. Even though you may have administrative access, you still will not be able to access it. You can try it from Explorer itself. (Need to enable option to show protected Operating System files.)

File Icons and List view

How to retrieve file icons associated with the file types and add them with the items of Listview in vb.net
I read about SHGetFileInfo but I didn't understand anything from that
please give me solution or please explain me ho system works with the .net controls in details
Having looked up SHGetFileInfo I can see why you're confused by it, but I think it might be slightly overkill for what I think you're trying to do i.e. enumerating the contents of a folder and adding items to the Listview.
If we have a form that contains a ListView and an ImageList, with the two related by having the ListView's LargeImageList property set to the ImageList, then here's how we put the contents of a folder into the ListView with the icons coming from the associated EXE file for each file.
Imports System.IO
Imports System.Drawing
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim dirInfo As DirectoryInfo
Dim fileInfo As FileInfo
Dim exePath As String
Dim exeIcon As Icon
dirInfo = New DirectoryInfo(path_to_some_folder
'We use this For...Each to iterate over the collection of files in the folder
For Each fileInfo In dirInfo.GetFiles
'We can only find associated exes by extension, so don't show any files that have no extension
If fileInfo.Extension = String.Empty Then
Else
'Use the function to get the path to the executable for the file
exePath = GetAssociatedProgram(fileInfo.Extension)
'Use ExtractAssociatedIcon to get an icon from the path
exeIcon = Drawing.Icon.ExtractAssociatedIcon(exePath)
'Add the icon if we haven't got it already, with the executable path as the key
If ImageList1.Images.ContainsKey(exePath) Then
Else
ImageList1.Images.Add(exePath, exeIcon)
End If
'Add the file to the ListView, with the executable path as the key to the ImageList's image
ListView1.Items.Add(fileInfo.Name, exePath)
End If
Next
End Sub
GetAssociatedProgram comes from developer.com
Public Function GetAssociatedProgram(ByVal FileExtension As _
String) As String
' Returns the application associated with the specified
' FileExtension
' ie, path\denenv.exe for "VB" files
Dim objExtReg As Microsoft.Win32.RegistryKey = _
Microsoft.Win32.Registry.ClassesRoot
Dim objAppReg As Microsoft.Win32.RegistryKey = _
Microsoft.Win32.Registry.ClassesRoot
Dim strExtValue As String
Try
' Add trailing period if doesn't exist
If FileExtension.Substring(0, 1) <> "." Then _
FileExtension = "." & FileExtension
' Open registry areas containing launching app details
objExtReg = objExtReg.OpenSubKey(FileExtension.Trim)
strExtValue = objExtReg.GetValue("").ToString
objAppReg = objAppReg.OpenSubKey(strExtValue & _
"\shell\open\command")
' Parse out, tidy up and return result
Dim SplitArray() As String
SplitArray = Split(objAppReg.GetValue(Nothing).ToString, """")
If SplitArray(0).Trim.Length > 0 Then
Return SplitArray(0).Replace("%1", "")
Else
Return SplitArray(1).Replace("%1", "")
End If
Catch
Return ""
End Try
End Function
At the end of all of that, when you run this code on this folder:
alt text http://www.philippursglove.com/stackoverflow/listview1.png
you should get:
alt text http://www.philippursglove.com/stackoverflow/listview2.png
If you know the file name of the file whose icon you want, you can use the System.Drawing.Icon.ExtractAssociatedIcon function for that purpose. e.g.
Icon ico = System.Drawing.Icon.ExtractAssociatedIcon(#"C:\WINDOWS\system32\notepad.exe");
You can also refer to my answer to a related question for more implementation details.