Get Current Network Profile using c#

Viewed 650

I am trying to get my Network profile which works in Powershell returning my network name and what im after the NetworkCategory. (See Below)

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

When in c# my GetNetworkProfile does not return anything.

        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();
        }
    }
}

Any ideas? I'm running Studio with elevated privileges.

I am aiming to be able to identify if the network category is public, and if it is then use Set-NetConnectionProfile to set it to Private within my application.

1 Answers

Well there is a .NET Library where you find classes to get the needed information

Link: 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);

Maybe this could help you?

Related