Windows File Protection (WFP, Windows 2000/XP) / System File Checker (SFC) 透過 **SFC API** 保護關鍵系統檔案不被覆寫/刪除。開發安裝程式、修補工具、安全掃描器時,常需**列舉受保護清單**或**檢測特定檔案是否受保護**。本文提供 C++Builder 可直接編譯的實作程式碼。
sfc.h (Platform SDK / Windows SDK)sfc.lib (專案連結設定加入)SfcGetNextProtectedFile:列舉下一個受保護檔案SfcIsFileProtected:檢測指定檔案是否受保護//---------------------------------------------------------------------------
#include
// 專案需連結 sfc.lib
//---------------------------------------------------------------------------
// 列出所有受保護檔案
void __fastcall ListAllProtectedFile(TStrings *pList)
{
PROTECTED_FILE_DATA data = {0};
data.FileNumber = 0; // 從頭開始
while (SfcGetNextProtectedFile(NULL, &data))
{
if (data.FileNumber != 0) // 略過初始項
{
pList->Add(data.FileName); // 檔案完整路徑
}
}
}
// 判斷單一檔案是否受保護
bool __fastcall IsFileProtected(String strFile)
{
WCHAR wszFileName[MAX_PATH];
MultiByteToWideChar(CP_ACP, 0, strFile.c_str(), -1, wszFileName, MAX_PATH);
return SfcIsFileProtected(NULL, wszFileName);
}
// 使用範例:按鈕點擊檢測
void __fastcall TForm1::Button1Click(TObject *Sender)
{
// ListAllProtectedFile(Memo1->Lines); // 列舉全部 (耗時較久)
if (IsFileProtected("E:\\Winnt\\system32\\subst1.exe"))
ShowMessage("受保護");
else
ShowMessage("未受保護");
}
//---------------------------------------------------------------------------
typedef struct _PROTECTED_FILE_DATA {
DWORD FileNumber; // 遞增序號,0 表開始
WCHAR FileName[MAX_PATH]; // 完整路徑 (Unicode)
} PROTECTED_FILE_DATA, *PPROTECTED_FILE_DATA;
| 作業系統 | 機制 | API |
|---|---|---|
| Windows 2000 / XP | WFP | SfcIsFileProtected, SfcGetNextProtectedFile |
| Windows Vista / 7 / 8 / 10 / 11 | Windows Resource Protection (WRP) | 同 API 相容,但保護範圍擴大 (登錄機碼、ACL 也受保護) |
現代替代:sfc /verifyonly (命令列)、PowerShell Get-SystemFileProtection、WMI Win32_ProtectedFile。
WCHAR)SfcIsFileProtected 仍可依據資料庫判斷是否屬受保護類別