以编程方式使用C#更改目录(文件夹)图标
我想使用C#更改Windows平台上特定文件夹图标的图标。您可以通过在以编程方式使用C#更改目录(文件夹)图标,c#,windows,C#,Windows,我想使用C#更改Windows平台上特定文件夹图标的图标。您可以通过在desktop.ini文件中指定文件夹图标来更新该图标 private static void ApplyFolderIcon(string targetFolderPath, string iconFilePath) { var iniPath = Path.Combine(targetFolderPath, "desktop.ini"); if (File.Exists(iniPath)) {
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 );
}
如果现在右键单击文件夹,您将看到图标已更新。在文件资源管理器中应用更改之前,可能需要一段时间
我一直在试图找到一种方法来立即应用更改,但到目前为止运气不佳。有一个shchangennotify
shell函数可以做到这一点,但它似乎不适用于文件夹
注意我们必须在开始时从
ini
文件中删除系统
和隐藏的
属性,否则文件。WriteAllText
将失败,因为您没有修改它的权限。@Prajwal:不幸的是,重复的问题回答得很差。现有的问题很好,但他们的问题是在更改图标之前忘记了特定文件夹中的删除desktop.ini
文件。它确实工作得很好。我刚刚在这里发布了一个完整的解决方案,我在这里搜索并找到了哪些链接,并对其进行了测试:在给出我的默认外观之后文件夹desktop.ini文件,我在文件夹中使用了“attrib+S”。我立刻在已经打开的资源管理器窗口中看到了带有图标的文件夹。再次删除该标志-文件夹看起来是默认的。这可行吗!?!?例如,“dir”命令不再显示该文件夹(默认情况下):将系统属性设置到文件夹确实起到了作用,并记录在中,但是它与用户操作“文件夹属性-自定义-更改图标”不完全相同。系统文件夹属性上的“隐藏”复选框变灰,而用户单击的图标应用的文件夹不是“系统”。谢谢,这是我找到的唯一一个以编程方式设置文件夹图标的工具。