我使用FilePathDialog.SelectedPath获取文件夹路径,我也知道图标的路径,但我不知道如何设置该文件夹的图标。
设置一些文件属性似乎很重要。
基于https://github.com/dimuththarindu/FIC-Folder-Icon-Changer,这是精简版本。
在您想要设置其属性的文件夹中,创建以下三个文件:
MyIcon.ico
您想要显示的图标。您可以使用不同的文件名。
desktop.ini - 包含以下文本
[.ShellClassInfo]
IconResource=MyIcon.ico,0
[ViewState]
Mode=
Vid=
FolderType=Generic
.hidden- 包含以下文本
desktop.ini
MyIcon.ico
我的情况下,文件类型采用UTF-8带BOM格式。
然后,您需要将所有三个文件的属性设置为:
隐藏
只读
最后,您需要通知系统发生了更改。
SHChangeNotify(0x08000000, 0x0000, (IntPtr)null, (IntPtr)null);
假设您创建了一个名为Resources的文件夹,并将三个文件放在其中。以下是设置图标的代码:
using System;
using System.IO;
using System.Runtime.InteropServices;
namespace SetFolderIcon
{
class Program
{
[DllImport("shell32.dll", CharSet = CharSet.Auto, SetLastError = true)]
private static extern void SHChangeNotify(
int wEventId, int uFlags, IntPtr dwItem1, IntPtr dwItem2);
static void Main(string[] args)
{
string location = $"C:\\Users\\Balint\\Desktop";
string folderPath = Path.Combine(location, "My Folder");
string desktopIniPath = Path.Combine(folderPath, "desktop.ini");
string iconPath = Path.Combine(folderPath, "MyIcon.ico");
string hiddenPath = Path.Combine(folderPath, ".hidden");
Directory.CreateDirectory(folderPath);
File.Copy($"Resources\\desktop.ini", desktopIniPath);
File.Copy($"Resources\\Klinng.ico", iconPath);
File.Copy($"Resources\\.hidden", hiddenPath);
File.SetAttributes(desktopIniPath,
File.GetAttributes(desktopIniPath)
| FileAttributes.Hidden
| FileAttributes.ReadOnly);
File.SetAttributes(iconPath,
File.GetAttributes(iconPath)
| FileAttributes.Hidden
| FileAttributes.ReadOnly);
File.SetAttributes(hiddenPath,
File.GetAttributes(hiddenPath)
| FileAttributes.Hidden
| FileAttributes.ReadOnly);
File.SetAttributes(folderPath,
File.GetAttributes(folderPath)
| FileAttributes.ReadOnly);
SHChangeNotify(0x08000000, 0x0000, (IntPtr)null, (IntPtr)null);
}
}
}
您需要编写 desktop.ini
文件。
[.ShellClassInfo]
IconResource=Icon.ico,0
IconFile=Icon.ico
IconIndex=0
[ViewState]
Mode=
Vid=
FolderType=Pictures
C# 代码
string dir = "Folder Path";
string[] lines = { "[.ShellClassInfo]", "IconResource=Icon.ico,0", "[ViewState]", "Mode=", "Vid=", "FolderType=Pictures" };
File.WriteAllLines(dir + @"\desktop.ini", lines);
图标资源:{图标路径},0
文件夹类型:通用
,文档
,图片
,音乐
,视频
如果需要更多信息,请查看这个 GitHub 项目:https://github.com/dimuththarindu/FIC-Folder-Icon-Changer
给文件夹分配图标基本上有两个步骤(如果计算创建文件夹,则可能是三个步骤):
在要创建图标的文件夹(“目标文件夹”)内创建一个desktop.ini文件。 将目标文件夹的属性设置为“系统”。
更多信息: