我想使用C#
在Windows平台上更改特定文件夹图标的图标答案 0 :(得分:8)
您可以通过在desktop.ini
文件
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 );
}
如果您现在右键单击该文件夹,您将看到图标已更新。在文件资源管理器中应用更改之前可能需要一段时间。
我一直试图找到一种方法立即应用这些更改,但到目前为止没有运气。有一个SHChangeNotify
shell函数可以做到这一点,但它似乎不适用于文件夹。
注意我们必须在开头从System
文件中删除Hidden
和ini
属性,否则File.WriteAllText
会失败,因为您没有权限修改它。