Reputation: 409
I want to change icon of particular folder's icons on Windows platform using C#
Upvotes: 1
Views: 3634
Reputation: 39072
You can update the folder icon by specifying it in the desktop.ini
file
private static void ApplyFolderIcon(string targetFolderPath, string iconFilePath)
{
var iniPath = Path.Combine(targetFolderPath, "desktop.ini");
if (File.Exists(iniPath))
{
//remove hidden and system attributes to make ini file writable
File.SetAttributes(
iniPath,
File.GetAttributes(iniPath) &
~( FileAttributes.Hidden | FileAttributes.System) );
}
//create new ini file with the required contents
var iniContents = new StringBuilder()
.AppendLine("[.ShellClassInfo]")
.AppendLine($"IconResource={iconFilePath},0")
.AppendLine($"IconFile={iconFilePath}")
.AppendLine("IconIndex=0")
.ToString();
File.WriteAllText(iniPath, iniContents);
//hide the ini file and set it as system
File.SetAttributes(
iniPath,
File.GetAttributes(iniPath) | FileAttributes.Hidden | FileAttributes.System );
//set the folder as system
File.SetAttributes(
targetFolderPath,
File.GetAttributes(targetFolderPath) | FileAttributes.System );
}
If you now right-click the folder, you will see that the icon is updated. It might take a while before the change is applied in the file explorer as well.
I have been trying to find a way to apply the changes immediately, but so far without luck. There is a SHChangeNotify
shell function that should do just that, but it doesn't seem to work with folders.
Note we have to remove the System
and Hidden
attributes from the ini
file in the beginning, otherwise File.WriteAllText
will fail because you don't have permissions to modify it.
Upvotes: 10