change folder icon using c#

173 Views Asked by At

i have a code that create a folder and add desktop.ini file and icon.ico file to change folder icon

string dir = path;
string[] lines = { "[.ShellClassInfo]", $"IconResource=Icon.ico,0", 
    "[ViewState]", "Mode=", "Vid=", "FolderType=Pictures" };
File.WriteAllLines(dir + @"\desktop.ini", lines);
DirectoryInfo dirInfo = new(folderpath + $"\\{name}");

// Set the directory to read-only.
dirInfo.Attributes |= FileAttributes.ReadOnly;
DirectoryInfo dirInfo2 = new(folderpath + $"\\{name}\\desktop.ini");
dirInfo2.Attributes |= FileAttributes.ReadOnly;
DirectoryInfo dirInfo3 = new(folderpath + $"\\{name}\\Icon.ico");
dirInfo3.Attributes |= FileAttributes.ReadOnly;
//refresh folder
SHChangeNotify(0x8000000, 0x1000, IntPtr.Zero, IntPtr.Zero);

now the folder icon is not changing:

enter image description here

but when i go to folder options i see that the icon has been set successfully:

enter image description here

And this:

enter image description here

And when I move the folder from it's place using file explorer the icon appears.

I tried to change folder icon. I expected the icon to appear but it didn't.

1

There are 1 best solutions below

0
Amr Omran On
private static void SetFolderCustomIcon(string folderPath, string iconPath)
{
    DirectoryInfo folderInfo = new DirectoryInfo(folderPath);

    if (!folderInfo.Exists)
        return;

    // Create desktop.ini and set the custom icon as a file icon
    string desktopIniPath = Path.Combine(folderPath, "desktop.ini");
    File.WriteAllText(desktopIniPath, "[.ShellClassInfo]\r\nIconFile=" + iconPath + "\r\nIconIndex=0");

    // Set the attributes of desktop.ini to hidden and system
    File.SetAttributes(desktopIniPath, File.GetAttributes(desktopIniPath) | FileAttributes.Hidden | FileAttributes.System);

    // Trigger a refresh of the folder's view
    SHChangeNotify(0x08000000, 0x0000, IntPtr.Zero, IntPtr.Zero);
}

[DllImport("shell32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern void SHChangeNotify(int wEventId, uint uFlags, IntPtr dwItem1, IntPtr dwItem2); 

to Use It

// Set the custom icon for the folder

    string FolderTochangeIcon = @"Path to Your Folder"
    string iconPath = @"Path to Your Folder\icon.ico";
    SetFolderCustomIcon(FolderTochangeIcon, iconPath);

Make Sure That Your Icon Size 128 X 128