2016-12-30 67 views

回答

5

改變的特定文件夾的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將失敗,因爲你沒有權限對其進行修改。

+1

感謝您使用最簡單的代碼。 +1 –

相關問題