I've read a few sources on this. I followed this accepted answer and am using Managed WiFi API to get the SSID if I am connected via WiFi. Here is my code:
private void setSSID() {
WlanClient wlan = new WlanClient();
Collection<String> connectedSsids = new Collection<string>();
foreach (WlanClient.WlanInterface wlanInterface in wlan.Interfaces) {
Wlan.Dot11Ssid ssid = wlanInterface.CurrentConnection.wlanAssociationAttributes.dot11Ssid;
connectedSsids.Add(new String(Encoding.ASCII.GetChars(ssid.SSID, 0, (int)ssid.SSIDLength)));
}
}
This will get the SSID perfectly if I am connected via WiFi but throws an exception if only connected via Ethernet. The ideal solution:
- Enter
setSSID()
(or something to similar effect) - Check if connected via Ethernet
- If so, return
null
/0
/undefined
- Else, return the SSID
(I have already got a check in if it's even connected to the network or not)
I have looked all over the WMI and the NetworkInformation namespace but neither provide what I am looking for.
Looking in WlanApi.cs, the exception is thrown here:
public Wlan.WlanConnectionAttributes CurrentConnection {
get {
int valueSize;
IntPtr valuePtr;
Wlan.WlanOpcodeValueType opcodeValueType;
Wlan.ThrowIfError(
Wlan.WlanQueryInterface(client.clientHandle, info.interfaceGuid, Wlan.WlanIntfOpcode.CurrentConnection, IntPtr.Zero, out valueSize, out valuePtr, out opcodeValueType));
try {
return (Wlan.WlanConnectionAttributes)Marshal.PtrToStructure(valuePtr, typeof(Wlan.WlanConnectionAttributes));
}
finally {
Wlan.WlanFreeMemory(valuePtr);
}
}
}
Also looked at: