使用C#获取当前的网络配置文件

问题描述

我试图获取可在Powershell中工作的网络配置文件,以返回我的网络名称以及NetworkCategory之后的即时消息。 (请参见下文)

InterfaceAlias   : Ethernet
InterfaceIndex   : 4
NetworkCategory  : Private
IPv4Connectivity : Internet
IPv6Connectivity : NoTraffic

在c#中,我的GetNetworkProfile不返回任何内容

        static void Main(string[] args)
        {
            PowerShell ps = PowerShell.Create();
            ps.AddScript("Get-NetConnectionProfile");
            Collection<PSObject> PSOutput = ps.Invoke();

            foreach (PSObject outputItem in PSOutput)
            {
                if (outputItem != null)
                {
                    Console.WriteLine($"Output line: [{outputItem}]");
                }
            }

            Console.WriteLine();
            Console.ReadLine();
        }
    }
}

有什么想法吗?我正在以提升的权限运行Studio

我的目标是能够识别网络类别是否为公共类别,然后在应用程序中使用Set-NetConnectionProfile将其设置为“私有”。

解决方法

有一个.NET库,您可以在其中找到用于获取所需信息的类

链接:https://docs.microsoft.com/en-us/dotnet/api/system.net.networkinformation?view=netcore-3.1

using Windows.Networking.Connectivity;

// Retrieve the ConnectionProfile.
ConnectionProfile internetConnectionProfile = NetworkInformation.GetInternetConnectionProfile();

// Pass the returned object to a function that accesses the connection data.
string connectionProfileInfo = GetConnectionProfileInfo(internetConnectionProfile);

也许这可以帮助您?