0

In my Visual Basic processing, I'm creating a number of folders. Is there a way, using VB code, I can change the icon displayed for these folders in File Explorer? I'm thinking I must need to change a property when I use the My.Computer.FileSystem.CreateDirectory but I'm not sure how to do it.

umitu
  • 2,423
  • 1
  • 10
  • 28
Ross from Brooklin
  • 293
  • 1
  • 5
  • 18
  • Just create a custom `desktop.ini` file. See here for an example: https://stackoverflow.com/questions/68941080/update-folder-icon-with-desktop-ini-instantly-change-c – Dai Oct 17 '21 at 14:50
  • Here's a C# question which is similar to this one. It should be easier to go from C# > VB vs C++ > VB https://stackoverflow.com/questions/6531898/c-sharp-how-to-set-folder-icon – Nathan Champion Oct 17 '21 at 16:47

1 Answers1

0

You can do it in this way:

Private Sub SetFolderIcon(ByVal folder As String, ByVal ico As Icon, Optional ByVal tip As String = "")
        If IO.Directory.Exists(folder) Then
        Try
            'Copy the icon from the resources into the project folder if it doesn't exist
            Dim iconFile As String = IO.Path.Combine(folder, "Icon.ico")
            If Not IO.File.Exists(iconFile) Then
                Using st As New IO.FileStream(iconFile, IO.FileMode.Create)
                    ico.Save(st)
                End Using
            End If

            'Set the hidden attribute for the icon file to be invisible
            Dim ifa As New IO.FileInfo(iconFile)
            ifa.Attributes = ifa.Attributes Or IO.FileAttributes.Hidden

            'Create a new Desktop.ini file in the folder
            Dim iniFile As String = IO.Path.Combine(folder, "Desktop.ini")
            If tip <> "" Then
                Dim iniStr() As String = {"[.ShellClassInfo]", "IconFile=Icon.ico", "IconIndex=0", "InfoTip=" & tip}
                IO.File.WriteAllLines(iniFile, iniStr)
            Else
                Dim iniStr() As String = {"[.ShellClassInfo]", "IconFile=Icon.ico", "IconIndex=0"}
                IO.File.WriteAllLines(iniFile, iniStr)
            End If

            'Set the system and hidden file attribute for the new Desktop.ini file
            Dim fa As New IO.FileInfo(iniFile)
            fa.Attributes = fa.Attributes Or IO.FileAttributes.System Or IO.FileAttributes.Hidden

            'Set the system attribute for the folder if it is not already set
            Dim di As New IO.DirectoryInfo(folder)
            If (di.Attributes And IO.FileAttributes.System) <> IO.FileAttributes.System Then
                di.Attributes = di.Attributes Or IO.FileAttributes.System
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message.ToString)
        End Try
    End If
End Sub

Then run the above code:

SetFolderIcon(folder, My.Resources.icon, "Custom folder")