以编程方式使用C#更改目录(文件夹)图标

时间:2016-12-30 08:05:29

标签: c# windows

我想使用C#

在Windows平台上更改特定文件夹图标的图标

1 个答案:

答案 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文件中删除Hiddenini属性,否则File.WriteAllText会失败,因为您没有权限修改它。