Search code examples
c#wifinetshssid

C# store each wlan profile in an ObservableCollection


I have to store each profile name in an Observable collection, but I don't know how to do this, I made a big part of the project, but it is how to acces to EACH profile name that I don't know how to do.

I saw people are using Substrings and IndexOf, I tried but the problem is that I have more than only one profile name to display so this isn't working.

I followed this tutorial: https://www.youtube.com/watch?v=Yr3nfHiA8Kk But it is showing how to do but with the Wifi currently connected

InitializeComponent();
            ObservableCollection<String> reseaux = new ObservableCollection<String>();

            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.FileName = "netsh.exe";
            //p.StartInfo.Arguments = "wlan show interfaces";
            p.StartInfo.Arguments = "wlan show profile";
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.Start();

        /*foreach (System.Diagnostics.Process profile in profile)
        {
            reseaux.Add(reseauName);
        }*/

        lesReseaux.ItemsSource = reseaux;

Solution

  • I don't have a way to test this at the moment, but based on the output you've shown in the image it appears that you could take all the output, split it into individual lines, split each line on the ':' character, and then select the second part from that split to get the name.

    But first, I think the argument to show is "profiles" (plural), and according to one of the comments you may need to use the full path to netsh.exe. So that code might look like:

    var startInfo = new ProcessStartInfo
    {
        FileName = Path.Combine(Environment.SystemDirectory, "netsh.exe"),
        Arguments = "wlan show profiles",
        UseShellExecute = false,
        RedirectStandardOutput = true,
    };
    
    var p = Process.Start(startInfo);
    p.WaitForExit();
    

    After this, the output from the command will be stored in p.StandardOutput (which is a StreamReader), and we can get it all as a string using .ReadToEnd():

    var output = p.StandardOutput
        // Get all the output
        .ReadToEnd()
        // Split it into lines
        .Split(new[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
        // Split each line on the ':' character
        .Select(line => line.Split(new[] {':'}, StringSplitOptions.RemoveEmptyEntries))
        // Get only lines that have something after the ':'
        .Where(split => split.Length > 1)
        // Select and trim the value after the ':'
        .Select(split => split[1].Trim());
    

    Now that we have an IEnumerable<string> of the names, we can initialize our collection with it:

    var reseaux = new ObservableCollection<string>(output);