107 lines
3.4 KiB
C#
107 lines
3.4 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Net.NetworkInformation;
|
|
using System.Diagnostics;
|
|
|
|
namespace EthernetSwitcher
|
|
{
|
|
public static class CurrentSettings
|
|
{
|
|
private static Settings _settings;
|
|
|
|
public static Settings Instance
|
|
{
|
|
get { return _settings ?? (_settings = Settings.Load()); }
|
|
}
|
|
|
|
public static void Save()
|
|
{
|
|
Instance.Save();
|
|
}
|
|
|
|
public static void Reload()
|
|
{
|
|
_settings = Settings.Load();
|
|
}
|
|
|
|
public static List<string> GetNetworkInterfaces()
|
|
{
|
|
try
|
|
{
|
|
// Use PowerShell to get consistent interface names
|
|
var output = ExecutePowerShell("Get-NetAdapter | Select-Object Name, Status | ForEach-Object { $_.Name + ' (' + $_.Status + ')' }");
|
|
|
|
if (string.IsNullOrEmpty(output))
|
|
{
|
|
// Fallback to NetworkInterface
|
|
return NetworkInterface.GetAllNetworkInterfaces()
|
|
.Select(ni => $"{ni.Name} ({ni.OperationalStatus})")
|
|
.OrderBy(name => name)
|
|
.ToList();
|
|
}
|
|
|
|
var interfaces = output.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)
|
|
.Where(line => !string.IsNullOrWhiteSpace(line.Trim()))
|
|
.Select(line => line.Trim())
|
|
.OrderBy(name => name)
|
|
.ToList();
|
|
|
|
return interfaces;
|
|
}
|
|
catch (Exception)
|
|
{
|
|
return new List<string>();
|
|
}
|
|
}
|
|
|
|
private static string ExecutePowerShell(string command)
|
|
{
|
|
try
|
|
{
|
|
var process = new Process
|
|
{
|
|
StartInfo = new ProcessStartInfo
|
|
{
|
|
FileName = "powershell.exe",
|
|
Arguments = $"-NoProfile -ExecutionPolicy Bypass -Command \"& {{{command}}}\"",
|
|
UseShellExecute = false,
|
|
RedirectStandardOutput = true,
|
|
RedirectStandardError = true,
|
|
CreateNoWindow = true
|
|
}
|
|
};
|
|
|
|
process.Start();
|
|
var output = process.StandardOutput.ReadToEnd();
|
|
var error = process.StandardError.ReadToEnd();
|
|
process.WaitForExit();
|
|
|
|
if (process.ExitCode != 0 && !string.IsNullOrEmpty(error))
|
|
{
|
|
Console.WriteLine($"PowerShell error in GetNetworkInterfaces: {error}");
|
|
}
|
|
|
|
return output;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.WriteLine($"Error executing PowerShell in GetNetworkInterfaces: {ex.Message}");
|
|
return "";
|
|
}
|
|
}
|
|
|
|
public static string GetCleanInterfaceName(string displayName)
|
|
{
|
|
if (string.IsNullOrEmpty(displayName))
|
|
return "";
|
|
|
|
var lastSpaceIndex = displayName.LastIndexOf(" (");
|
|
if (lastSpaceIndex > 0)
|
|
{
|
|
return displayName.Substring(0, lastSpaceIndex);
|
|
}
|
|
return displayName;
|
|
}
|
|
}
|
|
} |