【问题标题】:Get Current Network Profile using c#使用 c# 获取当前网络配置文件
【发布时间】:2023-03-25 08:08:02
【问题描述】:

我正在尝试获取在 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 在我的应用程序中将其设置为私有。

【问题讨论】:

  • 在foreach (PSObject outputItem in PSOutput) 上设置断点。接下来,将鼠标悬停在 ps 上并展开 -> 然后展开 Streams,然后展开 Error。那里有计数 > 0 吗?如果是这样,该错误说明了什么?我几乎可以打赌Provider Load Failure。如果是这种情况,那么您在 64 位 powershell 上运行 32 位应用程序,您不能这样做。您可以将构建 Platform Target 更改为 x64,重新构建并重试。让我知道这对你有什么影响。

标签: c# powershell networking network-programming


【解决方案1】:

有一个 .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);

也许这对你有帮助?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-28
    • 2023-03-31
    • 2011-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-07
    • 2023-03-22
    相关资源
    最近更新 更多