在早期的 Windows 版本(如 Windows 2000、XP)中,系統會預載數款經典小遊戲,例如「蜘蛛紙牌」、「空當接龍」、「掃雷」與「彈珠台」。雖然這些程式佔用空間不大,但在嚴格管控的企業環境或精簡系統映像時,開發人員常需以程式化方式移除它們。本文將示範如何透過 C# 呼叫 Win32 API、操作檔案系統與登錄,徹底刪除這四款遊戲及其快取備份。
遊戲執行檔通常位於 %SystemRoot%\System32,而 Windows 檔案保護機制會在 DllCache 目錄保留備份。因此刪除時必須同步清理這兩個位置。
DelSystemFourGames()private void DelSystemFourGames()
{
const int nChars = 260;
StringBuilder sysDir = new StringBuilder(nChars);
StringBuilder cacheDir = new StringBuilder(nChars);
// 取得 System32 路徑
GetSystemDirectory(sysDir, nChars);
sysDir.Append("\\");
// 取得 DllCache 路徑
GetSystemDirectory(cacheDir, nChars);
cacheDir.Append("\\DllCache\\");
// 定義四款遊戲的執行檔名稱
string[] games = { "sol.exe", "freecell.exe", "winmine.exe", "spider.exe" };
foreach (string game in games)
{
string sysPath = sysDir.ToString() + game;
string cachePath = cacheDir.ToString() + game;
if (File.Exists(sysPath)) File.Delete(sysPath);
if (File.Exists(cachePath)) File.Delete(cachePath);
}
// 彈珠台位於 Program Files\Windows NT\Pinball 目錄下
StringBuilder pinballDir = new StringBuilder(nChars);
GetSystemDirectory(pinballDir, nChars);
// 回到磁碟根目錄再拼接路徑
pinballDir.Remove(3, pinballDir.Length - 3); // 保留 "C:\"
pinballDir.Append("Program Files\\Windows NT\\Pinball");
if (Directory.Exists(pinballDir.ToString()))
{
DeleteDirectory(pinballDir.ToString()); // 遞迴刪除整個目錄
string pinballCache = cacheDir.ToString() + "pinball.exe";
if (File.Exists(pinballCache)) File.Delete(pinballCache);
}
}
private bool FileInDirectory(string fileName, string dirPath)
{
try
{
DirectoryInfo dir = new DirectoryInfo(dirPath);
foreach (FileInfo f in dir.GetFiles())
{
if (f.Name.Equals(fileName, StringComparison.OrdinalIgnoreCase))
return true;
}
}
catch { }
return false;
}
public static void DeleteDirectory(string path)
{
try
{
if (!path.EndsWith(Path.DirectorySeparatorChar.ToString()))
path += Path.DirectorySeparatorChar;
foreach (string entry in Directory.GetFileSystemEntries(path))
{
if (Directory.Exists(entry))
{
DeleteDirectory(Path.Combine(path, Path.GetFileName(entry)));
}
else
{
FileInfo fi = new FileInfo(entry);
if ((fi.Attributes & FileAttributes.ReadOnly) != 0)
fi.Attributes = FileAttributes.Normal;
File.Delete(entry);
}
}
Directory.Delete(path, true);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
在按鈕點擊事件或表單載入時直接呼叫:
private void btnRemoveGames_Click(object sender, EventArgs e)
{
DelSystemFourGames();
MessageBox.Show("系統內建遊戲已移除完成。");
}
DllCache。透過 P/Invoke 取得系統目錄、配合標準檔案 I/O 操作,即可達成移除系統預設遊戲的需求。此技巧同樣適用於其他需批次清理系統檔案的情境,展現了 C# 與底層 API 互操作的彈性。