簡體   English   中英

以編程方式使用C#更改目錄(文件夾)圖標

[英]Change Directory (folder) icon using C# programmatically

我想使用C#更改Windows平台上特定文件夾圖標的圖標

您可以通過在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函數應該執行此操作,但是它似乎不適用於文件夾。

請注意,我們必須在開始時從ini文件中刪除SystemHidden屬性,否則File.WriteAllText將失敗,因為您沒有修改它的權限。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM