範例:搭配 .NET Framework 使用 WMI 事件提供者
適用於:SQL Server
下列範例會使用 WMI 事件提供者在 C# 中建立應用程式,以傳回 SQL Server 預設安裝實例上發生之所有資料定義語言 (DDL) 事件的事件數據。
範例
此範例會使用下列命令檔編譯:
set compiler_path=C:\WINNT\Microsoft.NET\Framework\v2.0.50110
%compiler_path%\csc %1
using System;
using System.Management;
class SQLWEPExample
{
public static void Main(string[] args)
{
string query = @"SELECT * FROM DDL_EVENTS " ;
// Default namespace for default instance of SQL Server
string managementPath =
@"\\.\root\Microsoft\SqlServer\ServerEvents\MSSQLSERVER";
ManagementEventWatcher watcher =
new ManagementEventWatcher(new WqlEventQuery (query));
ManagementScope scope = new ManagementScope (managementPath);
scope.Connect();
watcher.Scope = scope;
Console.WriteLine("Watching...");
while (true)
{
ManagementBaseObject obj = watcher.WaitForNextEvent();
Console.WriteLine("Event!");
foreach (PropertyData data in obj.Properties)
{
Console.Write("{0}:", data.Name);
if (data.Value == null)
{
Console.WriteLine("<null>");
}
else
{
Console.WriteLine(data.Value.ToString());
}
}
Console.WriteLine("-----");
Console.WriteLine();
Console.WriteLine();
}
}
}
相關內容
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應