1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Windowsでフォルダのサムネイル(アイコン)を変更する方法

Posted at

はじめに

こんにちは、ただのぶたぁです。
個人開発をしている中でパソコン内のフォルダにサムネイル(アイコン)を設定する方法を探していたのですが、あまり情報が出なかったため書きました。

ディレクトリ構成

├── sample
│    ├── desktop.ini    フォルダのアイコンを設定するファイル
│    └── image.ico    アイコン画像
│
├── main.py     Pythonでアイコンを設定するスクリプト
└── main.go     Goでアイコンを設定するスクリプト

手順

コマンドプロンプトを操作できる言語であればGo, Pythonにかかわらずできます。

1. desktop.iniを作成する
2. desktop.iniに必要なことを書き込む
3. desktop.iniを隠しフォルダにする (attrib +h)
4. 親ディレクトリ(今回ではsampleフォルダ)に対してシステム権限を付与する (attrib +s)

desktop.iniの内容

desktop.ini
[.ShellClassInfo]
IconResource = image.ico,0
  • IconResource = { アイコンのパス },0
    • { アイコンのパス } の部分に image.ico の絶対パスまたは相対パスを指定
    • 0 はアイコンのインデックス( 通常は 0 でOK )

実装例

Go

main.go
package main

import (
	"fmt"
	"os"
	"os/exec"
)

func main() {
	// desktop.iniのパスとアイコンのパスを指定
	desktopIniPath := "./sample/desktop.ini"
	imageIcoPath := "image.ico" // desktop.iniから見たアイコンのパス

	// desktop.iniを作成して内容を書き込む
	file, err := os.Create(desktopIniPath)
	if err != nil {
		fmt.Println("desktop.iniを作成できませんでした:", err)
		return
	}
	defer file.Close()

	// .ShellClassInfo の設定を書き込む
	_, err = file.WriteString(fmt.Sprintf("[.ShellClassInfo]\nIconResource=%s,0\n", imageIcoPath))
	if err != nil {
		fmt.Println("desktop.iniに書き込みができませんでした:", err)
		return
	}

	// attribコマンドでdesktop.iniを隠しファイルにする
	cmd := exec.Command("attrib", "+h", desktopIniPath)
	err = cmd.Run()
	if err != nil {
		fmt.Println("desktop.iniを隠しファイルにできませんでした:", err)
		return
	}

	// sampleフォルダにシステム属性を付与
	cmd = exec.Command("attrib", "+s", "./sample")
	err = cmd.Run()
	if err != nil {
		fmt.Println("sampleフォルダにシステム属性を付与できませんでした", err)
		return
	}

	fmt.Println("処理が終わりました")
}

Python

main.py
import subprocess

# desktop.iniのパスを指定
desktopIniPath = "./sample/desktop.ini"
imageIcoPath = "image.ico"  # desktop.iniから見たアイコンのパス

# desktop.iniを作成し、アイコンの設定を書き込む
with open(desktopIniPath, 'w') as f:
    f.write(f'[.ShellClassInfo]\nIconResource="{imageIcoPath}",0\n')

# コマンドプロンプトでattribコマンドを実行して、desktop.iniを隠しファイルにする
subprocess.run(['attrib', '+h', desktopIniPath])

# sampleフォルダにシステム属性を付与
subprocess.run(['attrib', '+s', './sample'])

print("処理が終わりました")

反映までに時間がかかる問題

プログラムを実行して、ある程度の時間がたたないとサムネイル(アイコン)が反映されない場合があります。
おそらく原因は、Windowsのキャッシュが影響して、変更がすぐに反映されないためだと思われます。

基本的には、しばらく時間が経てば自動的に反映されるので、特に気にする必要はありません。

もし長時間経っても反映されない場合は、パソコンエクスプローラー を再起動する ことでキャッシュがリフレッシュされ、反映される可能性があります。

参考サイト

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?