回答編集履歴

2

C# のエラー処理の追加 Guidで取得する様に修正

2024/02/29 07:06

投稿

juner
juner

スコア754

test CHANGED
@@ -28,8 +28,14 @@
28
28
  using System.Runtime.InteropServices;
29
29
  if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
30
30
  throw new PlatformNotSupportedException("required windows only");
31
- var machineId = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\SQMClient")?.GetValue("MachineId");
31
+ using var subKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\SQMClient");
32
+ if (subKey is not { } _subKey || _subKey.GetValue("MachineId") is not string _machineId)
33
+ throw new Exception("not found registry key \"SOFTWARE\\Microsoft\\SQMClient\\MachineId\"");
34
+ // _machineId はこの時点で string
35
+ // Guid 化
36
+ var machineId = Guid.Parse(_machineId);
37
+ // 大文字で出力したいならこう
32
- Console.WriteLine($"{machineId}");
38
+ Console.WriteLine($"{machineId:B}".ToUpperInvariant());
33
39
  ```
34
40
 
35
41
  で取れます。

1

C# のソースコードを追加

2024/02/29 06:55

投稿

juner
juner

スコア754

test CHANGED
@@ -21,6 +21,17 @@
21
21
  Get-ItemPropertyValue "HKLM:\SOFTWARE\Microsoft\SQMClient" -Name "MachineId"
22
22
  ```
23
23
 
24
+ C# なら
25
+
26
+ ```csharp
27
+ using Microsoft.Win32;
28
+ using System.Runtime.InteropServices;
29
+ if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
30
+ throw new PlatformNotSupportedException("required windows only");
31
+ var machineId = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\SQMClient")?.GetValue("MachineId");
32
+ Console.WriteLine($"{machineId}");
33
+ ```
34
+
24
35
  で取れます。
25
36
 
26
37
  以上。