Click here to Skip to main content
15,884,177 members
Articles / Programming Languages / Visual Basic
Tip/Trick

Exporting and Importing Wireless Settings Using Netsh in VB.NET (Updated)

Rate me:
Please Sign up or sign in to vote.
4.50/5 (9 votes)
19 Apr 2015CPOL2 min read 42.7K   10   8
How to export and import wireless settings using Netsh in VB.NET (updated)

I. Introduction

Wireless settings can be exported and imported using netsh. In this tip, I will refer to the wlan (wireless local area network) part of the netsh command line program for the actions explained. Besides importing and exporting profiles and their wireless information, other actions can be performed such as: deleting wireless profiles (also called networks), blocking certain networks from showing up in the wireless connections list, etc. One example is netsh wlan delete will delete a wireless network. Next, let’s see the form setup so everyone reading the tip can understand how the project was designed before I step into the code.

II. Setup Of Project

For this project, I have 2 forms in the setup of the project. For importing, I have Form1 which imports the data using an open file dialog box which can accept multiple items. For exporting profiles, the Profiles form exports specific profiles the user checks from the checked list box. Figure 1 is my design of Form1 and Figure 2 shows the design of the Profiles form. The profiles form is used to display all the wireless profiles installed on the computer. After a person checks off the profiles they want export into an XML file, netsh saves that file to the XML settings export path chosen back on Form1.

Figure 1 – Form 1 Design

Image 1

Figure 2 – Profiles Form Design

Image 2

III. The Code

First, I will go over the importation code which is very simple. The import SSID and Network Profile Information button (also called BtnImport) imports the wireless information from XML information files. Below in Figure 3, I show the BtnImport_click event code that does multiple item importation in one click (by sending data to ImportProfile Function in Figure 7). In Figure 4, I show the BtnExport_Click event which opens the Profiles Form and allows the user to select the profiles to export. In Figure 5, I am loading the profiles in the Profiles_Load event which fills the checkedlistbox with items. In Figure 6, I show the code for BtnSelectProfiles_Click event (the only button in figure 2). Finally, Figure 8 shows the code for the Log Subroutine I use in my BtnImport_Click event.

Figure 3 – BtnImport_Click event
VB.NET
 Private Sub BtnImport_Click(sender As Object, e As EventArgs) Handles BtnImport.Click
    Dim result As System.Windows.Forms.DialogResult
    OpenFileDialog1.Filter = "Xml Files (*.xml)|*.xml;"
    OpenFileDialog1.Multiselect = True
    result = OpenFileDialog1.ShowDialog()
    If result = Windows.Forms.DialogResult.OK Then
        If OpenFileDialog1.FileName <> "" Then
            Dim importprocess As Process = New Process
            importprocess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
            'simple application logging added to provided
            'error status as to whether the code completed successfully
            If OpenFileDialog1.FileNames.Length >= 2 Then   'if more than one filename selected
                        'loop through the files selected and import them.
                For j As Integer = 0 To OpenFileDialog1.FileNames.Length - 1
                    If ImportProfile(OpenFileDialog1.FileNames.GetValue(j)) = True Then
                        Log("successfully imported profile:" + OpenFileDialog1.FileName)
                    Else
                        Log("Error profile:" + OpenFileDialog1.FileName + _
                        " did not import properly. Please reimport!")
                    End If
                Next j
            Else
                TxtOpenPath.Text = OpenFileDialog1.FileName
                If ImportProfile(OpenFileDialog1.FileName) = True Then
                    MsgBox("successfully imported profile:" + OpenFileDialog1.FileName)
                Else
                    MsgBox("Error profile:" + OpenFileDialog1.FileName + _
                    " did not import properly. Please reimport!")
                End If
                System.Threading.Thread.Sleep(2000)
            End If
        End If
    End If
End Sub
Figure 4 – BtnExport_Click event
VB.NET
Private Sub BtnExport_Click(sender As Object, e As EventArgs) Handles BtnExport.Click
    Dim result As System.Windows.Forms.DialogResult

    result = FolderBrowserDialog1.ShowDialog()
    If result = Windows.Forms.DialogResult.OK Then
        If FolderBrowserDialog1.SelectedPath <> "" Then
            TxtSavePath.Text = FolderBrowserDialog1.SelectedPath
            TxtSavePath.Enabled = False
            Profiles.Show()
        End If
    End If
End Sub
Figure 5 – Profiles_Load Event
VB.NET
Private Sub Profiles_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    ' Dim Profiles As List(Of String) = New List(Of String)
    Dim tempstr As String
    Dim tmpstr1 As String
    Dim tmpstr2 As String
    Dim i As Integer
    Dim wifistart As ProcessStartInfo = New ProcessStartInfo
    Dim wifiprofiles As Process = New Process
    Dim baddata As String
    Dim profilesread As StreamReader
    wifistart.CreateNoWindow = True
    wifistart.WindowStyle = ProcessWindowStyle.Hidden
    wifistart.FileName = "netsh"
    wifistart.Arguments = "wlan show profiles"
    wifistart.UseShellExecute = False
    wifistart.RedirectStandardOutput = True
    wifiprofiles = Process.Start(wifistart)

    Dim profilefile As StreamReader = wifiprofiles.StandardOutput
    If File.Exists(Application.StartupPath + "\Profiles.wpro") Then
        File.Delete(Application.StartupPath + "\Profiles.wpro")
    End If
    Dim profilewrite As StreamWriter = _
      New StreamWriter(Application.StartupPath + "\Profiles.wpro", False)
    Do Until wifiprofiles.StandardOutput.EndOfStream
        profilewrite.WriteLine(profilefile.ReadLine)
    Loop
    profilewrite.Close()
    wifiprofiles.StandardOutput.Close()

    profilesread = New StreamReader(Application.StartupPath + "\Profiles.wpro")
    Do While Not profilesread.EndOfStream

        If i >= 9 Then
            tempstr = profilesread.ReadLine
            If tempstr.IndexOf("All User Profile") <> -1 Then
                tmpstr2 = tempstr.Remove(tempstr.IndexOf("All"), 22)
                ' MsgBox("All user profile replace:" + tmpstr2)
                lstNetworkProfiles.Items.Add(tmpstr2)
            End If
            If tempstr.IndexOf("Current User Profile") <> -1 Then
                tmpstr1 = tempstr.Remove(tempstr.IndexOf("Current"), 22)
                lstNetworkProfiles.Items.Add(tmpstr1)
                ' MsgBox("current user profile replace:" + tmpstr1)
            End If

        Else
            baddata = Nothing
            baddata = profilesread.ReadLine()
        End If
        i = i + 1
    Loop

    System.Threading.Thread.Sleep(3000)
End Sub
Figure 6 – BtnSelectProfiles_Click Event
VB.NET
Private Sub BtnSelectProfiles_Click(sender As Object, e As EventArgs) Handles BtnSelectProfiles.Click

    Dim importprocess As Process = Process.Start("c:\Windows\System32\cmd.exe")
    importprocess.StartInfo.WindowStyle = ProcessWindowStyle.Normal
    'importprocess.StartInfo.UseShellExecute = False
    ' importprocess.StartInfo.CreateNoWindow = True
    'importprocess()

    Dim i As Integer
    System.Threading.Thread.Sleep(2000)

    For i = 0 To lstNetworkProfiles.Items.Count - 1
        If lstNetworkProfiles.GetItemChecked(i) = True Then
            My.Computer.Keyboard.SendKeys("netsh wlan export profile name=" + _
              Chr(34) + Trim(lstNetworkProfiles.Items.Item(i).ToString) + Chr(34) + _
              " folder=" + Chr(34) + Form1.TxtSavePath.Text + Chr(34))
            My.Computer.Keyboard.SendKeys("{Enter}")
        Else

            ' importprocess = Process.Start("netsh", _
            '  "wlan export profile name=" + Chr(34) + _
            ' lstNetworkProfiles.Items.Item(i).ToString + Chr(34) + _
            ' " folder=" + Chr(34) + Form1.TxtSavePath.Text + Chr(34))
        End If
    Next

    System.Threading.Thread.Sleep(2000)

End Sub
Figure 7 – ImportProfile Function
VB.NET
 Function ImportProfile(filename As String) As Boolean
    Dim importprocess As Process = New Process
    importprocess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
    importprocess = Process.Start("c:\Windows\System32\netsh.exe", _
                       "wlan add profile file=" + Chr(34) + _
                       filename + Chr(34) + " user=current")
    importprocess.Close()
    Return True
End Function
Figure 8 – Log Sub
VB.NET
Sub Log(text As String)
      Dim logfile As IO.StreamWriter = New IO.StreamWriter(Application.StartupPath, True)
      logfile.WriteLine(text)
      logfile.Close()
  End Sub

History

  • Add a subroutine to change up Import process and avoid extra code. In addition, I added a logging function (can be removed from the source code or changed as necessary).

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralIncredibly good... Pin
Edward Omowa29-Apr-15 3:39
professionalEdward Omowa29-Apr-15 3:39 
GeneralRe: Incredibly good... Pin
jeffery c29-Apr-15 8:52
jeffery c29-Apr-15 8:52 
GeneralQick & Dirty Pin
sx200818-Apr-15 3:57
sx200818-Apr-15 3:57 
GeneralRe: Qick & Dirty Pin
jeffery c18-Apr-15 4:16
jeffery c18-Apr-15 4:16 
Understood, I make edits from time to time. So, I will make that edit and re-upload the source code soon (if I get the chance later today or Monday). Thanks for noticing it. Most of the newer/big projects, I try to make reusable subs but sometimes I forget on the smaller projects/blog posts. This was more a sample of how to do something.
jeffery

GeneralRe: Qick & Dirty Pin
jeffery c18-Apr-15 10:54
jeffery c18-Apr-15 10:54 
GeneralPretty cool. Pin
Slow Eddie16-Apr-15 10:14
professionalSlow Eddie16-Apr-15 10:14 
GeneralRe: Pretty cool. Pin
jeffery c16-Apr-15 10:47
jeffery c16-Apr-15 10:47 
Questionupdated version with windows wlan apis and full source code download links Pin
jeffery c7-Jan-14 12:00
jeffery c7-Jan-14 12:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.