Last active
April 18, 2024 15:01
-
-
Save tommyready/df468fb96667fea3862e387656198c58 to your computer and use it in GitHub Desktop.
Using C# to Disable and Enable a Network Adapter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
amazing work! ty so much 🙂