Skip to content

Instantly share code, notes, and snippets.

@tommyready
Last active April 18, 2024 15:01
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tommyready/df468fb96667fea3862e387656198c58 to your computer and use it in GitHub Desktop.
Save tommyready/df468fb96667fea3862e387656198c58 to your computer and use it in GitHub Desktop.
Using C# to Disable and Enable a Network Adapter
using System;
using System.Diagnostics;
using System.Threading.Tasks;
namespace NetworkAdaptersUtility
{
class Program
{
static void Main(string[] args)
{
string networkInterfaceName = "";
try
{
networkInterfaceName = args[0]; // Set Network Interface from Arguments
Task TaskOne = Task.Factory.StartNew(() => DisableAdapter(networkInterfaceName) );
TaskOne.Wait();
Task TaskTwo = Task.Factory.StartNew(() => EnableAdapter(networkInterfaceName) );
}
catch (Exception e)
{
// Log Error Message
using (EventLog eventLog = new EventLog("Application"))
{
eventLog.Source = "NetworkAdaptersUtility";
if( e.GetType().IsAssignableFrom(typeof(System.IndexOutOfRangeException)) ) {
eventLog.WriteEntry("No Network Interface Provided", EventLogEntryType.Error, 101, 1);
} else
{
eventLog.WriteEntry(e.Message, EventLogEntryType.Error, 101, 1);
}
}
}
}
static void EnableAdapter(string interfaceName)
{
ProcessStartInfo psi = new ProcessStartInfo("netsh", "interface set interface \"" + interfaceName + "\" enable");
Process p = new Process();
p.StartInfo = psi;
p.Start();
}
static void DisableAdapter(string interfaceName)
{
ProcessStartInfo psi = new ProcessStartInfo("netsh", "interface set interface \"" + interfaceName + "\" disable");
Process p = new Process();
p.StartInfo = psi;
p.Start();
}
}
}
@MakeGywer
Copy link

Thank you very much 👍
This code helps a lot, by testing Error-Handling in my TCP-Service , when connection ist broken.

I have extended it , with return values :

`using System.Diagnostics;
using System.Linq;
using System.Net.NetworkInformation;
using System.Threading;
using System.Threading.Tasks;

namespace TcApp.SharedCore.Utils
{

static public class NetworkAdaptersUtility
{

    private static void ExecuteWaitProcess(string cmd, string args) 
    {

        ProcessStartInfo psi = new ProcessStartInfo(cmd, args);
        Process p = new Process();
        p.StartInfo = psi;
        p.Start();
        p.WaitForExit();
    }

    public static Task<bool> EnableAdapterAsync(string interfaceName, int timeOut= 2000)
    {
        bool enabled = false;
        int timeElapsed = 0;
        int timeWait = 100;
        var locker = new object();

        return Task.Run(() =>
        {

            ExecuteWaitProcess("netsh", "interface set interface \"" + interfaceName + "\" enable");

            do
            {
                lock (locker) enabled = IsAdpapterEnabled(interfaceName);
                Thread.Sleep(timeWait);
                lock (locker) timeElapsed += timeWait;

            } while (!enabled && timeElapsed < timeOut);
            return enabled;
        });
    }

    public static Task<bool> DisableAdapterAsync(string interfaceName, int timeOut = 2000)
    {
        bool disabled = false;
        int timeElapsed = 0;
        int timeWait = 100;
        var locker = new object();
        

        return Task.Run(() =>
        {
            ExecuteWaitProcess("netsh", "interface set interface \"" + interfaceName + "\" disable");

            do 
            {
                lock(locker) disabled = IsAdpapterDisabled(interfaceName);
                Thread.Sleep(timeWait);
                lock (locker)  timeElapsed += timeWait;

            } while (!disabled && timeElapsed < timeOut);
            return disabled;
        });
    }


    /// https://stackoverflow.com/a/314322/19305596
    public static bool IsAdpapterEnabled(string interfaceName) {
        var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
        NetworkInterface selectedInterface = networkInterfaces
                                                .FirstOrDefault(n => n.Name == interfaceName);
        if (selectedInterface == null) 
        {
            return false;
        }
        return selectedInterface.OperationalStatus == OperationalStatus.Up;
    }

    public static bool IsAdpapterDisabled(string interfaceName)
    {
        var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
        NetworkInterface selectedInterface = networkInterfaces
                                                .FirstOrDefault(n => n.Name == interfaceName);
        if (selectedInterface == null)
        {
            // NetworkInterface.GetAllNetworkInterfaces() liefert nur die available Netzwerk-Apdapter zurück;
            return true;
        }
        // rückgabe ist nicht Enabled
        return selectedInterface.OperationalStatus != OperationalStatus.Up;
    }
}

}`

@lyf-is-coding
Copy link

amazing work! ty so much 🙂

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment