how to get default network connection name used via C#? - c#

I need get it independent if the network connection is active or not.
I need get only dial up connection.
in this picture Claro is default netowork connection name.
Have no idea how do this. I hope this is clear. Thanks in advance!

To find the currently selected default connection for connecting to the internet, which can be set in a couple of ways, you need to read the registry key HKCU\RemoteAccess InternetProfile. This will contain the name of the adapter.
Now the fun part: you will need to use DotRas.
Once you have this downloaded, installed, and reference in your project, you can use code similar to the following:
// Get the default adapter
string defaultAdapter = Registry.GetValue(#"HKEY_CURRENT_USER\RemoteAccess", "InternetProfile", "") as string;
foreach (RasConnection connection in RasConnection.GetActiveConnections())
{
if (connection.EntryName.Equals(defaultAdapter, StringComparison.InvariantCultureIgnoreCase))
{
if (connection.GetConnectionStatus().ConnectionState == RasConnectionState.Connected)
{
// Do something
}
}
// Done searching
break;
}

is this what you where looking for?
using System.Net.NetworkInformation;
class Program
{
static void Main(string[] args)
{
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
Console.WriteLine(nic.NetworkInterfaceType);
Console.WriteLine(nic.Name);
}
}
}
if you find out what string it puts for NetworkInterfaceType with modems then you can put a if statement in there

Related

full path as the filename

Maybe someone knows a simple solution to my problem.
I do not know the entry of the file so it's not a static value.
It can be changed through the BizTalk gui and there we have a URI through the receiveport. But I do not believe it's accessible that easy. What I want to do is write out the full path as the filename. It works well with the messageID where the file is given a specific filepath name. But the Path-Name where the file was dropped is not working that well.
I keep getting this error :
Message:
Object reference not set to an instance of an object.
the message resource is present but the message is not found in the string/message table
-Does not say me much
Below you can see a snip from my code
internal static string UpdateMacroPathProperty(IBaseMessage baseMessage, string macroPathProperty, string macroDefsFile)
{
if (macroName == "MessageID")
{
contextPropertyValue = baseMessage.MessageID.ToString();
}
else if (macroName == "SourceFileName")
{
contextPropertyValue = Directory.GetCurrentDirectory();
}
}
This is an specific created pipeline. Has anyone encountered this problem or can point me in the right way.
I know that BizTalk has a built in function for this, BizTalk Server: List of Macros as the %SourceFileName% but I'm trying to save this as logs in a specific map structure so that it does not get processed.
It's adapter dependent; some adapters will use the FILE adapter's namespace even though they're not the file adapter, but this is the kind of logic that I've used in the past for this:
string adapterType = (string)pInMsg.Context.Read("InboundTransportType",
"http://schemas.microsoft.com/BizTalk/2003/system-properties");
string filePath = null;
if (adapterType != null)
{
if (adapterType == "FILE")
{
filePath = (string)pInMsg.Context.Read("ReceivedFileName",
"http://schemas.microsoft.com/BizTalk/2003/file-properties");
}
else if (adapterType.Contians("SFTP") && !adapterType.Contains("nsoftware"))
// nsoftware uses the FTP schema
{
filePath = (string)pInMsg.Context.Read("ReceivedFileName",
"http://schemas.microsoft.com/BizTalk/2012/Adapter/sftp-properties");
}
else if (adapterType.Contains("FTP"))
{
filePath = (string)pInMsg.Context.Read("ReceivedFileName",
"http://schemas.microsoft.com/BizTalk/2003/ftp-properties");
}
}
And then you can just fall back to the MessageID if you can't get the file path from any of these.

How can I detect if Microsoft Edge is installed?

I'm writing a windows form application (c#) and I need to detect whether the user have "Microsoft-Edge" installed in his/her machine or not.
I'm currently using this registry location:
[HKEY_CLASSES_ROOT\Local Settings\Software\Microsoft\Windows\CurrentVersion\AppModel\PackageRepository\Packages\Microsoft.MicrosoftEdge_20.10240.16384.0_neutral__8wekyb3d8bbwe]
"Path"="C:\\Windows\\SystemApps\\Microsoft.MicrosoftEdge_8wekyb3d8bbwe"
With a regex after the "Microsoft.MicrosoftEdge". If the "path" exist then I know edge is installed.
Is there a better way to detect edge? would it be better if I detect that I'm running on Windows 10 and by default Win10 come with edge? What is the best way for that?
In case you want to have a small program getting that version number:
static void Main(string[] args)
{
string EdgeVersion = string.Empty;
//open the registry and parse through the keys until you find Microsoft.MicrosoftEdge
RegistryKey reg = Registry.ClassesRoot.OpenSubKey(#"Local Settings\Software\Microsoft\Windows\CurrentVersion\AppModel\PackageRepository\Packages");
if (reg != null)
{
foreach (string subkey in reg.GetSubKeyNames())
{
if (subkey.StartsWith("Microsoft.MicrosoftEdge"))
{
//RegEx: (Microsoft.MicrosoftEdge_)(\d +\.\d +\.\d +\.\d +)(_neutral__8wekyb3d8bbwe])
Match rxEdgeVersion = null;
rxEdgeVersion = Regex.Match(subkey, #"(Microsoft.MicrosoftEdge_)(?<version>\d+\.\d+\.\d+\.\d+)(_neutral__8wekyb3d8bbwe)");
//just after that value, you need to use RegEx to find the version number of the value in the registry
if ( rxEdgeVersion.Success )
EdgeVersion = rxEdgeVersion.Groups["version"].Value;
}
}
}
Console.WriteLine("Edge Version(empty means not found): {0}", EdgeVersion);
Console.ReadLine();
}
Thank you for the registry link for finding the version number.
If you're on the desktop or mobile version of Windows 10 then Edge is pre-installed and can't be uninstalled.
To detect if running on Windows 10 use the System.Environment.OSVersion property or the Version Helper functions. (See also https://msdn.microsoft.com/en-us/library/windows/desktop/ms724832(v=vs.85).aspx)
If you want to detect the default browser you should see How to determine the Windows default browser (at the top of the start menu)
Relevant to 15.11.2016:
The only way that I found working is to use this registry location:
[HKEY_CLASSES_ROOT\Local Settings\Software\Microsoft\Windows\CurrentVersion\AppModel\PackageRepository\Packages\Microsoft.MicrosoftEdge_20.10240.16384.0_neutral__8wekyb3d8bbwe]
"Path"="C:\\Windows\\SystemApps\\Microsoft.MicrosoftEdge_8wekyb3d8bbwe"
With a regex after the "Microsoft.MicrosoftEdge".
If the "path" exist then I know edge is installed.
In reference to other answers: my installation of Windows 10 does not have this key: Microsoft.MicrosoftEdge_20.10240.16384.0_neutral__8wekyb3d8bbwe
In:
[HKEY_CLASSES_ROOT\Local Settings\Software\Microsoft\Windows\CurrentVersion\AppModel\PackageRepository\Packages\]
Instead, it has the following keys:
Microsoft.MicrosoftEdge_38.14393.0.0_neutral__8wekyb3d8bbwe
Microsoft.MicrosoftEdge_40.15063.674.0_neutral__8wekyb3d8bbwe
The following code could be used to detect if Edge is installed:
class Program
{
static void Main(string[] args)
{
var edgeFound = false;
using (var key = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(#"Local Settings\Software\Microsoft\Windows\CurrentVersion\AppModel\PackageRepository\Packages\"))
{
if (key != null)
{
foreach (var subkey in key.GetSubKeyNames())
{
if (subkey.StartsWith("Microsoft.MicrosoftEdge_"))
{
edgeFound = true;
break;
}
}
}
}
Console.Write(edgeFound);
Console.ReadLine();
}
}

Detect when ethernet cable is plugged

I'm trying to detect when an Ethernet cable is plugged-in or unplugged but i have some probleme and i don't know if i'm doing this good or not.
I'm using NetworkChange.NetworkAddressChanged
to detect when the network change
and then NetworkInterface.GetAllNetworkInterfaces() for checking if Ethernet connexion is available or not with the property .OperationalStatus.
But when i search for the Ethernet connexion in all the network interfaces, it return me what i'm looking for, but it always return me the Bluetooth connection with it.
Here is the code :
public Form1()
{
InitializeComponent();
NetworkChange.NetworkAddressChanged += new NetworkAddressChangedEventHandler(AddressChangedCallback);
Console.ReadLine();
}
static void AddressChangedCallback(object sender, EventArgs e)
{
NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface myInterface in adapters)
{
//if (n.Description.ToLower().Contains("ethernet")){
//if (n.NetworkInterfaceType.ToString().ToLower().Contains("ethernet")){
IPInterfaceProperties properties = n.GetIPProperties();
if (myInterface.NetworkInterfaceType == NetworkInterfaceType.Ethernet)
{
Console.WriteLine(myInterface.Description + " ........... : " + myInterface.OperationalStatus);
Console.WriteLine("NetworkInterfaceType : " + myInterface.NetworkInterfaceType);
}
}
}
At the beginning, i was trying to check the name of the connection and looks if contains the "Ethernet" word, but it appears (if i'm not wrong) sometimes the connection name does not contain "Ethernet".
Do you have some tips for always bring the good connection (without the bluetooth)?
Am i wrong in my approach?
I'm testing it on a Surface Pro 3... but maybe i have the Bluetooth problem because of that?
Despite that, i need it to work even on device like this.
This can be done by checking its operational status as:
foreach (System.Net.NetworkInformation.NetworkInterface net in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces())
{
if (net.OperationalStatus ==
System.Net.NetworkInformation.OperationalStatus.Up)
Console.WriteLine("N/w connected");
else
Console.WriteLine("N/w not connected");
}
This links shows how to do it with Powershell, but one of the cases uses WMI.
http://www.powershellmagazine.com/2013/04/04/pstip-detecting-wi-fi-adapters/
And this links shows a interesting property that can help sometimes:
https://msdn.microsoft.com/en-us/library/aa394217(v=vs.85).aspx
GatewayCostMetric
Data type: uint16 array
Access type: Read-only Array
of integer cost metric values (ranging from 1 to 9999) to be used in
calculating the fastest, most reliable, or least resource-intensive
routes. This argument has a one-to-one correspondence with the
DefaultIPGateway property.

Discovering all computers and their shares on local network in C# [duplicate]

There are a lot of questions about getting the name and IP addresses of the local machine and several about getting IP addresses of other machines on the LAN (not all answered correctly). This is different.
In windows explorer if I select Network on the side bar I get a view of local machines on my LAN listed by machine name (in a windows workgroup, anyway). How do I get that same information programatically in C#?
You can try using the System.DirectoryServices namespace.
var root = new DirectoryEntry("WinNT:");
foreach (var dom in root.Children) {
foreach (var entry in dom.Children) {
if (entry.Name != "Schema") {
Console.WriteLine(entry.Name);
}
}
}
You need to broadcast an ARP request for all IPs within a given range. Start by defining the base IP on your network and then setting an upper identifier.
I was going to write up some code examples etc but it looks like someone has covered this comprehensively here;
Stackoverflow ARP question
This seems to be what you are after: How get list of local network computers?
In C#: you can use Gong Solutions
Shell Library
(https://sourceforge.net/projects/gong-shell/)
public List<String> ListNetworkComputers()
{
List<String> _ComputerNames = new List<String>();
String _ComputerSchema = "Computer";
System.DirectoryServices.DirectoryEntry _WinNTDirectoryEntries = new System.DirectoryServices.DirectoryEntry("WinNT:");
foreach (System.DirectoryServices.DirectoryEntry _AvailDomains in _WinNTDirectoryEntries.Children)
{
foreach (System.DirectoryServices.DirectoryEntry _PCNameEntry in _AvailDomains.Children)
{
if (_PCNameEntry.SchemaClassName.ToLower().Contains(_ComputerSchema.ToLower()))
{
_ComputerNames.Add(_PCNameEntry.Name);
}
}
}
return _ComputerNames;
}

How to find the windows dialing rules in .NET

This should be simple, but isn't apparently. Since..Windows 3 or so, there is a control panel called Phone or Phone & Modem. In that control panel is a bunch of information about how a modem would dial up, assuming you have a modem hooked up. For example, do you need to dial 9 to get out, what is the area code, and so forth. How can i access this information programmatically? I am using C# .NET 2010.
You are going to need to use Tapi in Windows or pull the information from the registry. According to Microsoft Tapi 3.0 was not designed to be used from managed code, though the first link seems to have done it.
Some articles to look at:
Tapi3.0 Application Development
VB.Net accessing TAPI Dialing Rules
From Link #2
Take a look at these TAPI functions:
lineGetTranslateCaps
lineTranslateAddress
lineTranslateDialog
lineSetCurrentLocation
lineGetCountry
tapiGetLocationInfo
The info is stored in the Registry at: HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Telephony\Locations
I couldn't find a way to access it through a .Net TAPI wrapper (after a not so long search) so I fired up procmon an found where it was stored in the registry, and here's the code that accesses it (you can adapt it to your specific needs):
RegistryKey locationsKey =
Registry.LocalMachine.OpenSubKey(#"SOFTWARE\Microsoft\Windows\CurrentVersion\Telephony\Locations");
if (locationsKey == null) return;
string[] locations = locationsKey.GetSubKeyNames();
foreach (var location in locations)
{
RegistryKey key = locationsKey.OpenSubKey(location);
if (key == null) continue;
Console.WriteLine("AreaCode {0}",key.GetValue("AreaCode"));
Console.WriteLine("Country {0}",(int) key.GetValue("Country"));
Console.WriteLine("OutsideAccess {0}", key.GetValue("OutsideAccess"));
}
Note :
I recommend to use an official API if there is a .net compatible one.
This code is not guaranteed to work on other OSes than Win 7
If you need to prompt the user to fill in these details you can start the configuration tool using :
Process.Start(#"C:\Windows\System32\rundll32.exe",#"C:\Windows\System32\shell32.dll,Control_RunDLL C:\Windows\System32\telephon.cpl");
Bit more code to get the prefix
class Program
{
static void Main(string[] args)
{
string rootLocation = #"SOFTWARE\Microsoft\Windows\CurrentVersion\Telephony\Locations";
getRegistryValues(rootLocation);
Console.ReadLine();
}
public static void getRegistryValues(string rootLocation)
{
RegistryKey locationsKey =
Registry.LocalMachine.OpenSubKey(rootLocation);
if (locationsKey == null) return;
string[] locations = locationsKey.GetSubKeyNames();
Console.WriteLine(locations.Length.ToString());
foreach (var location in locations)
{
Console.WriteLine(location.ToString());
RegistryKey key = locationsKey.OpenSubKey(location);
if (key == null) continue;
foreach (string keyName in key.GetValueNames())
{
if (keyName.Equals("Prefixes"))
{
string[] Prefixes = ((string[])(key.GetValue(keyName)));
Console.Write("Prefixes ");
foreach (string prefix in Prefixes)
{
Console.Write(prefix);
}
}
else
{
Console.WriteLine(keyName + " {0}", key.GetValue(keyName));
}
}
getRegistryValues(rootLocation+#"\"+location);
}
}

Categories

Resources