Skip to content

Instantly share code, notes, and snippets.

@tommyready
Last active April 18, 2024 15:01
Show Gist options
  • 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();
}
}
}
@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