最近負責的案子是要在 Windows 的設備中定時回傳資料到伺服器,包含一些對 Windows 的操作,第一次製作類似這樣的程式,寫了很多沒有寫過的東西。
一般在 Windows 下取得資訊或者操作都可以直接引用 Windows API
但是因為防火牆相關的 API 是用 Netfw.h
所以在使用上會和一般的 Windows API 不太一樣,所以在這邊紀錄一下
這邊使用的是套件 Vanara : https://github.com/dahall/Vanara
把大部分的 Windows API 都包裝成 .Net core 的形狀,這樣就不還要引用 function 還有寫 enum 或 class
非常方便的套件
using Vanara.InteropServices;
using static Vanara.PInvoke.FirewallApi;
using var pMgr = ComReleaserFactory.Create(new INetFwMgr());
using var pPol = ComReleaserFactory.Create(pMgr.Item.LocalPolicy);
using var pProf = ComReleaserFactory.Create(pPol.Item.GetProfileByType(NET_FW_PROFILE_TYPE.NET_FW_PROFILE_CURRENT));
Console.WriteLine(pProf.Item.FirewallEnabled);
NET_FW_PROFILE_TYPE 這個 Type 分別可以取得 Windows 底下防火牆的三種狀態
私人網路,網域網路,還有公用網路的狀態