473,729 Members | 2,235 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Get associated Icon based on file type not actual file

I am building this SQL Server database app in which i can store files. In
order to display files I want to have the app show the associated icon for
the extension of the file that is in the database. Therefore the file doesnt
really exist on the user's hard drive. All the file extracting techniques
require that I have the actual file on the drive in order to get an icon for
it. There is a workaround for this: i could create dummy files with the
correct extension and get the icon for them but that is kind of messy. Can
someone help me create/find a function like this
Function GetIcon(Extensi on as String) as Drawing.Icon

Thanks in advice
Nov 21 '05 #1
5 3167
"IcingDeath via DotNetMonster.c om" <fo***@DotNetMo nster.com> wrote in
message news:54******** ***@DotNetMonst er.com...
|I am building this SQL Server database app in which i can store files. In
| order to display files I want to have the app show the associated icon for
| the extension of the file that is in the database. Therefore the file
doesnt
| really exist on the user's hard drive. All the file extracting techniques
| require that I have the actual file on the drive in order to get an icon
for
| it. There is a workaround for this: i could create dummy files with the
| correct extension and get the icon for them but that is kind of messy. Can
| someone help me create/find a function like this
| Function GetIcon(Extensi on as String) as Drawing.Icon
i came up with this a few years back when learning vb.net...hope it helps
you...

Imports Microsoft.Win32
Imports System.Runtime. InteropServices

Public Class fileAssociation

#Region " structures "

Private Structure SHFILEINFO
Public iconHandle As IntPtr
Public iconIndex As Integer
Public attributes As Integer
<MarshalAs(Unma nagedType.ByVal TStr, SizeConst:=260) > _
Public displayName As String
<MarshalAs(Unma nagedType.ByVal TStr, SizeConst:=80)> _
Public typeName As String
End Structure

#End Region

#Region " interop "

Private Declare Function SHGetFileInfo Lib "shell32.dl l" ( _
ByVal pszPath
As String, _
ByVal
dwFileAttribute s As Integer, _
ByRef psfi As
SHFILEINFO, _
ByVal
cbFileInfo As Integer, _
ByVal uFlags
As Integer _
) As IntPtr

#End Region

#Region " internal classes"

Class associationCons tants

#Region " constants "

Public Const SHGFI_ICON As Integer = &H100
Public Const SHGFI_SMALLICON As Integer = &H1
Public Const SHGFI_LARGEICON As Integer = &H0

#End Region

End Class

Class fileAssociation Exception

#Region " interfaces "

Inherits Exception

#End Region

#Region " methods "

Public Sub New(ByVal message As String)
MyBase.New(mess age)
End Sub

#End Region

End Class

#End Region

#Region " methods "

Public Shared Function ApplicationName (ByVal ext As String) As String
Dim registeredExten sion As RegistryKey =
Registry.Classe sRoot.OpenSubKe y(ext)
ApplicationName = registeredExten sion.GetValue(" ")
registeredExten sion.Close()
End Function

Public Shared Function ApplicationIcon (ByVal ext As String, Optional ByVal
largeIcon As Boolean = False) As Icon
Dim applicationName As String = ApplicationPath (ext)
If applicationName Is Nothing OrElse applicationName = "" Then
Throw New fileAssociation Exception("Asso ciated icon not found.")
End If
Dim imagePointer As IntPtr
Dim fileInfo As New SHFILEINFO()
fileInfo.displa yName = New String(Chr(0), 260)
fileInfo.typeNa me = New String(Chr(0), 80)
Dim iconSize As Integer = IIf(largeIcon,
associationCons tants.SHGFI_LAR GEICON, associationCons tants.SHGFI_SMA LLICON)
imagePointer = SHGetFileInfo( _
applicationName , 0, fileInfo, _
Marshal.SizeOf( fileInfo), _
associationCons tants.SHGFI_ICO N Or
iconSize _
)
Return System.Drawing. Icon.FromHandle (fileInfo.iconH andle)
End Function

Public Shared Function ApplicationPath (ByVal ext As String) As String
Dim associatedAppli cation As RegistryKey
Dim registeredExten sion As RegistryKey
Dim properties() As String
Try
registeredExten sion = Registry.Classe sRoot.OpenSubKe y(ext)
Dim applicationName As String = registeredExten sion.GetValue(" ")
associatedAppli cation =
Registry.Classe sRoot.OpenSubKe y(applicationNa me & "\shell\open\co mmand")
properties = Split(associate dApplication.Ge tValue(""), """")
Catch ex As Exception
Throw New fileAssociation Exception("Asso ciated application not found."
& vbCrLf & vbCrLf & ex.Message)
Finally
registeredExten sion.Close()
associatedAppli cation.Close()
End Try
If properties Is Nothing OrElse properties.Leng th = 1 Then Return ""
Return properties(1)
End Function

#End Region

End Class
Nov 21 '05 #2
I really like your approach! Thanks... a lot!
--
Message posted via http://www.dotnetmonster.com
Nov 21 '05 #3
no problem...hope it works for what you need.
"IcingDeath via DotNetMonster.c om" <fo***@DotNetMo nster.com> wrote in
message news:54******** ***@DotNetMonst er.com...
|I really like your approach! Thanks... a lot!
|
|
| --
| Message posted via http://www.dotnetmonster.com
Nov 21 '05 #4
Using your code and other code on the internet as well some of my own I made
the extended icon class....
Its a good wrapper....
Note that although your method is nice cause you avoid read/writes from the
disk it is not very reliable....
Check for example icon for ".mdb" using the registry method vs the dummy file
method.
anyway here goes.....

------------------------ Code Start ------------------------------------------
--------------
Imports System.Runtime. InteropServices
Imports System.Drawing, System.Drawing. Imaging
Imports Microsoft.Win32
Public Class ExtendedIcon
'Inherits Drawing.Icon Declared NotInheritable. .. as if there was nothing
wrong with it!

#Region " FileInfo API"
#Region " Constants"
Private Const SHGFI_ICON = &H100
Private Const SHGFI_SMALLICON = &H1
Private Const SHGFI_LARGEICON = &H0
#End Region
#Region " Structures"
Private Structure SHFILEINFO

Public hIcon As IntPtr
Public iIcon As Integer
Public dwAttributes As Integer

<VBFixedString( 260), MarshalAs(Unman agedType.ByValT Str, SizeConst:
=260)> _
Public szDisplayName As String

<VBFixedString( 80), MarshalAs(Unman agedType.ByValT Str, SizeConst:=80)
_

Public szTypeName As String

End Structure
#End Region
Private Declare Function SHGetFileInfo Lib "shell32" Alias
"SHGetFileInfoA " _
(ByVal pszPath As String, _
ByVal dwFileAttribute s As Integer, _
ByRef psfi As SHFILEINFO, _
ByVal ByValcbFileInfo As Integer, _
ByVal uFlags As Integer) As Integer
#End Region 'Get Icon from a file
#Region " IconInfo API"

<DllImport("gdi 32.dll", SetLastError:=T rue)> _
Private Shared Function DeleteObject(By Val hObject As IntPtr) As Boolean
End Function

<DllImport("use r32.dll", CallingConventi on:=CallingConv ention.Cdecl)> _
Private Shared Function GetIconInfo(ByV al hIcon As IntPtr, ByRef
piconinfo As ICONINFO) As Boolean
End Function

Private Structure ICONINFO
Dim fIcon As Boolean
Dim xHotspot As Integer
Dim yHotspot As Integer
Dim hbmMask As IntPtr
Dim hbmColor As IntPtr
End Structure

#End Region 'Correct alpha blending
Private Base As Icon 'The underlying icon class
#Region " Original Constructors"
Public Sub New(ByVal IconFile As String)
Base = New Icon(IconFile)
End Sub
Public Sub New(ByVal Original As Icon, ByVal Size As Size)
Base = New Icon(Original, Size)
End Sub
Public Sub New(ByVal Type As System.Type, ByVal Resource As String)
Base = New Icon(Type, Resource)
End Sub
Public Sub New(ByVal Stream As IO.Stream)
Base = New Icon(Stream)
End Sub
Public Sub New(ByVal Stream As IO.Stream, ByVal Width As Integer, ByVal
Height As Integer)
Base = New Icon(Stream, Width, Height)
End Sub
#End Region
#Region " Original Methods"
Public Function Clone() As ExtendedIcon
Return New ExtendedIcon(CT ype(Base.Clone, Icon))
End Function
Public Function CreateObjRef(By Val RequestedType As System.Type) As
System.Runtime. Remoting.ObjRef
Return Base.CreateObjR ef(RequestedTyp e)
End Function
Public Sub Dispose()
Base.Dispose()
End Sub
Public Shared Function FromHandle(ByVa l Handle As IntPtr) As ExtendedIcon
Return New ExtendedIcon(Ic on.FromHandle(H andle))
End Function
Public Function GetLifeTimeServ ice() As Object
Return Base.GetLifetim eService
End Function
Public Function InitializeLifeT imeService() As Object
Return Base.Initialize LifetimeService ()
End Function
Public Sub Save(ByVal ToStream As IO.Stream)
Base.Save(ToStr eam)
End Sub
#End Region
#Region " Original Properties"
Public ReadOnly Property Handle() As IntPtr
Get
Return Base.Handle
End Get
End Property
Public ReadOnly Property Height() As Integer
Get
Return Base.Height
End Get
End Property
Public ReadOnly Property Size() As Drawing.Size
Get
Return Base.Size
End Get
End Property
Public ReadOnly Property Width() As Integer
Get
Return Base.Width
End Get
End Property
#End Region
#Region " Added Constructors"
Friend Sub New(ByVal Prototype As Icon)
Base = Prototype
End Sub
Public Sub New(ByVal Stream As IO.Stream, ByVal Size As Size)
Me.New(Stream, Size.Width, Size.Height)
End Sub
Public Sub New(ByVal Buffer As Byte())
Dim Stream As New BufferStream(Bu ffer)
Base = New Icon(Stream)
End Sub
Public Sub New(ByVal Buffer As Byte(), ByVal Size As Size)
Me.New(Buffer, Size.Width, Size.Height)
End Sub
Public Sub New(ByVal Buffer As Byte(), ByVal Width As Integer, ByVal
Height As Integer)
Dim Stream As New BufferStream(Bu ffer)
Base = New Icon(Stream, Width, Height)
End Sub
#End Region
#Region " Added Methods"
Public Function ToBitmap() As Drawing.Bitmap
Dim Info As New ICONINFO
GetIconInfo(Bas e.Handle, Info)
Dim bmp As Bitmap = Bitmap.FromHbit map(Info.hbmCol or)
DeleteObject(In fo.hbmColor)
DeleteObject(In fo.hbmMask)
If Bitmap.GetPixel FormatSize(bmp. PixelFormat) < 32 Then
Return Base.ToBitmap
End If

Dim bmData As Imaging.BitmapD ata
Dim bmBounds As New Rectangle(0, 0, bmp.Width, bmp.Height)

bmData = bmp.LockBits(bm Bounds, _
ImageLockMode.R eadOnly, _
bmp.PixelFormat )

Dim dstBitmap As New Bitmap(bmData.W idth, _
bmData.Height, _
bmData.Stride, _
PixelFormat.For mat32bppArgb, _
bmData.Scan0)

Dim x, y As Integer
Dim IsAlphaBitmap As Boolean = False

For y = 0 To bmData.Height - 1
For x = 0 To bmData.Width - 1
Dim PixelColor As Color
PixelColor = Color.FromArgb( Marshal.ReadInt 32(bmData.Scan0 ,
(bmData.Stride * y) + (4 * x)))
If PixelColor.A > 0 And PixelColor.A < 255 Then
IsAlphaBitmap = True
Exit For
End If
Next
If IsAlphaBitmap Then Exit For
Next

bmp.UnlockBits( bmData)

If IsAlphaBitmap Then
Return New Bitmap(dstBitma p)
Else
Return New Bitmap(Base.ToB itmap)
End If
End Function 'Correct alpha blending, picked this up somewhere on the net
Public Shared Function FromFileExtensi on(ByVal Extension As String, ByVal
Method As FileExtensionMe thod, Optional ByVal Size As IconSize = IconSize.
Small) As ExtendedIcon
Select Case Method
Case FileExtensionMe thod.DummyFile
'Create a dummy file in the Internet Cache special folder
Dim TheFile As New IO.FileInfo(Env ironment.GetFol derPath
(Environment.Sp ecialFolder.Int ernetCache) & "\Dummy." & Extension)
Dim TheIcon As Icon
If Not TheFile.Exists Then 'Dont want to stumble uppon
something
TheFile.Create. Close() 'Just created the file and closed
the stream
TheIcon = Extract(TheFile .FullName, Size)
TheFile.Delete( ) 'We created it so lets kill it
Else
TheIcon = Extract(TheFile .FullName, Size) 'Dont delete
anything that was already there
End If
Return New ExtendedIcon(Th eIcon)
Case FileExtensionMe thod.Registry
Dim AppPath As String
AppPath = ApplicationPath (Extension) 'Get the associated
application path from the registry
Return New ExtendedIcon(Ex tract(AppPath, Size)) 'return it's
icon
End Select
End Function
Public Shared Function FromAnyFile(ByV al FilePath As String, Optional
ByVal Size As IconSize = IconSize.Small) As ExtendedIcon
Return New ExtendedIcon(Ex tract(FilePath, Size))
End Function
#End Region
#Region " Support Methods"
Private Shared Function Extract(ByVal File As String, ByVal Size As
IconSize) As System.Drawing. Icon

Dim aSHFileInfo As SHFILEINFO
Dim cbFileInfo As Integer
Dim uflags As Integer
Dim Icon As System.Drawing. Icon

Select Case Size
Case IconSize.Large
uflags = SHGFI_ICON Or SHGFI_LARGEICON
Case Else
uflags = SHGFI_ICON Or SHGFI_SMALLICON
End Select

cbFileInfo = Marshal.SizeOf( aSHFileInfo)

SHGetFileInfo(F ile, 0, aSHFileInfo, cbFileInfo, uflags)

Icon = System.Drawing. Icon.FromHandle (aSHFileInfo.hI con)

Return Icon

End Function
Private Shared Function ApplicationName (ByVal ext As String) As String
Dim registeredExten sion As RegistryKey = Registry.Classe sRoot.
OpenSubKey(ext)
ApplicationName = registeredExten sion.GetValue(" ")
registeredExten sion.Close()
End Function
Private Shared Function ApplicationPath (ByVal ext As String) As String
Dim associatedAppli cation As RegistryKey
Dim AppName As String = ApplicationName (ext)
Dim properties() As String
Try
associatedAppli cation = Registry.Classe sRoot.OpenSubKe y(AppName &
"\shell\open\co mmand")
properties = Split(associate dApplication.Ge tValue(""), """")
Catch ex As Exception
Exit Function
Finally
associatedAppli cation.Close()
End Try
If properties Is Nothing OrElse properties.Leng th = 0 Then Return ""
Dim S As String
For Each S In properties
If Dir(S) <> "" And S <> "" Then
Return S
End If
If InStr(S, " ") <> 0 Then
Dim SS() As String = S.Split
Dim f As String
For Each f In SS
If InStr(f, "\") = 0 Then f = Environment.Sys temDirectory
& "\" & f
If Dir(f) <> "" And f <> "" Then
Return f
End If
Next
End If
Next
End Function
#End Region
#Region " Support Classes"
Private Class BufferStream
Inherits IO.Stream
Private Buffer As Byte()
Private Pos As Long
Sub New(ByVal B As Byte())
Buffer = B
End Sub
Public Overrides ReadOnly Property CanRead() As Boolean
Get
Return False
End Get
End Property

Public Overrides ReadOnly Property CanSeek() As Boolean
Get
Return False
End Get
End Property

Public Overrides ReadOnly Property CanWrite() As Boolean
Get
Return False
End Get
End Property

Public Overrides Sub Flush()
End Sub

Public Overrides ReadOnly Property Length() As Long
Get
Return Buffer.Length
End Get
End Property

Public Overrides Property Position() As Long
Get
Return Pos
End Get
Set(ByVal Value As Long)
Pos = Value
End Set
End Property

Public Overrides Function Read(ByVal inbuffer() As Byte, ByVal offset
As Integer, ByVal count As Integer) As Integer
Dim i As Long, ib As Integer
'Stupid Icon class reads everything at once...
'I gave it a length of 160MB and it still tried to read it at
once
For i = Pos + offset To Pos + offset + count - 1
inbuffer(ib) = Buffer(i)
ib += 1
Next
End Function

Public Overrides Function Seek(ByVal offset As Long, ByVal origin As
System.IO.SeekO rigin) As Long
Select Case origin
Case IO.SeekOrigin.B egin
Pos = offset
Case IO.SeekOrigin.C urrent
Pos += offset
Case IO.SeekOrigin.E nd
Pos = Buffer.Length - offset
End Select
End Function

Public Overrides Sub SetLength(ByVal value As Long)
End Sub

Public Overrides Sub Write(ByVal buffer() As Byte, ByVal offset As
Integer, ByVal count As Integer)
End Sub
Sub Dispose()
Erase Buffer
End Sub
End Class 'For constructor using byte array
#End Region
End Class
#Region " Enums"
Public Enum FileExtensionMe thod
Registry 'Check the windows Registry... Not 100%
DummyFile ' Create a dummy file with the extension and let windows decide
End Enum
Public Enum IconSize
Small ' eeeer Small :)
Large ' If not small then...
End Enum
#End Region

------------------------------------------ Code End --------------------------
-----------------
--
Message posted via http://www.dotnetmonster.com
Nov 21 '05 #5
| Note that although your method is nice cause you avoid read/writes from
the
| disk it is not very reliable....

interesting. i tried it with .mdb and got a typical ms access icon...i do
see your point though, since i tried .jpg and got a shell command for it to
be opened by the image viewer on xp rather than, say, ms paint.

i'm glad you've got what you need.

all the best.
Nov 21 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
13163
by: Danny Pressley | last post by:
I have a VS.NET 2003 Visual C++ MFC Application Project in which I added a new resource file, I then added an icon to this new resource file and did a rebuild and got the following error: "fatal error CVT1100: duplicate resource. type:ICON, name:1, language:0x0409". But the resource ID is unique and only located in the new Resource1.h and MyResourceFile.rc files. Any ideas why this error is occuring? To generate the issue real quick, you...
7
8070
by: Shane Story | last post by:
I want to be able to get the icon associated with a certain file extension. I can read the registry hkey_classes to get the ext. then look to the other key for default icon. How can I then extract the icon in file x at index 1 or whatever? Again, I am not dealing with a file exactly but with a string path of the file that has an extension.
3
2421
by: Brian Henry | last post by:
How would you get the associated icon for the file type of a file with a certain extension? like BMP, JPEG, MPEG, etc etc find their default icon using the File Types listing that associates the extension with an icon in windows. thanks!
4
1249
by: Giovanni pepe | last post by:
I have download from site Microsoft the procedure for Get Associated Icon from File Article is : "How to use the SHGetFileInfo function to get the icons that are associated with files in Visual Basic .NET" But i have the problem.... Then Icon .txt - .Xml and other is a looked badly, while others are looked at well I have set in imagelist trasparentcolor = Trasparent but nothing...
4
3829
by: techspirit | last post by:
Hi all, 1) I found out from the vb.net group that it is possible to get an associated icon for a file. My requirement is to display all programs from the Start Menu for the user along with the associated icons. While I am able to list the programs correctly, the icons that get displayed alongside are the ones for the folders. The form has listview and imagelist controls on it. I shall paste the code here. 2) I was also wondering why...
1
1207
by: Neo | last post by:
please tell me, how get icon structure associated with extension? if my file extention is (Doc) then how and where i get icon of document file? regards, Mohammad Omer Nasir
1
1384
by: gevald123 | last post by:
I'm storing system files in a sql server database, as "image" datatype fields. In my front end (vb .net 1.1) I'd like to display these files in a listview with the "Windows Explorer" feel and look. I'm strugling to retreive the apropriate icon for the file extension, so far all the code I saw, it seems like that I have to pass a file name that exists in Windows O/S system file, in my case I'm not dealing with files strored in the O/S,...
5
6677
by: =?Utf-8?B?TG9hbldvbGY=?= | last post by:
I'm working on a Windows Explorer-like application. What is the best way to find out what application is set to open a particular type of file? Is there a function to do this? Do I have to go through the registry and check ClassesRoot? Also, once I have the application, I want to be able to get the icon for that application. How would I get this?
1
8239
by: laredotornado | last post by:
Hi, When I save out an HTML file to my desktop (I'm using Windows XP), it saves with the Firefox icon, presumably because I have Firefox as the default application to open my HTML files. Is it possible to have the desktop icon be the favicon.ico file of the web site from which I'm saving the page? Thanks, - Dave
0
8913
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8761
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9426
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9200
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8144
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6722
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6016
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4795
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3238
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.