execute asterisk cli command C# - c#

I need a help with executing asterisk cli commands using C#. I'm able to open terminal window and start asterisk (see the code below), but dont know how to for example execute "sip show peers" command in CLI. Is there any possible way to do it?
using System;
using System.Diagnostics;
namespace runGnomeTerminal
{
class MainClass
{
public static void ExecuteCommand(string command)
{
Process proc = new System.Diagnostics.Process ();
proc.StartInfo.FileName = "/bin/bash";
proc.StartInfo.Arguments = "-c \" " + command + " \"";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start ();
while (!proc.StandardOutput.EndOfStream) {
Console.WriteLine (proc.StandardOutput.ReadLine ());
}
}
public static void Main (string[] args)
{
ExecuteCommand("gnome-terminal -x bash -ic 'cd $HOME; sudo asterisk -vvvvr; bash'");
}
}
}

All you triing to do is overkill. You just need ask asterisk for command, no need in bash or terminal.
Process proc = new System.Diagnostics.Process ();
proc.StartInfo.FileName = "/usr/sbin/asterisk";
proc.StartInfo.Arguments = "-rx \" " + command + " \"";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start ();
But please note, that command start NEW asterisk process, so not optimal. Best way is use asterisk AMI interface(which is just tcp connection, so much less resources use) and issue AMI action COMMAND.
There are number of already developed AMI interfaces, including C# one.

You can execute asterisk cli commands directly from bash, just -x to the asterisk command.
For example ExecuteCommand("gnome-terminal -x bash -ic 'cd $HOME; sudo asterisk -rx "sip show peers"; bash'");.

Related

CLI Commands + Arguments are not executing correctly.

I`m working in the CLI commands in my Visual Studio C# application. This application does the interface with the Flash Programmer 2 (Texas Instruments Software to bootload the firmware in CC2560) using CLI ( Command-Line interface).
I checked some examples in StackOverflow, but I didn't have success to implement the solutions.
Steps of my application:
Select the serial port
Open the console
execute the srfprog.exe
execute the command line (srfprog -t soc(COM84,CC2650) -e -p -v -f c:\test.bin )
Check if the programming was a success
My file is located in: D:\Projects\Test_Fixture\Test_Fixture_Visual_Studio\SmartRF Tools\Flash Programmer 2\bin\srfprog.exe
When I execute this in my CMD (windows) the Prompt window shows
After this screen pop up I sent the commands to program the chip
srfprog -t soc(COM84,CC2650) -e -p -v -f c:\test.bin
This command will program and verify the code in the microcontroller CC2650 as show in the screenshot below:
The programming is perfect.
However when I run(Click the button - Load Firmware) my application open and close Shell window immediately. As shown in the figure below
My code is below:
private void button2_Click(object sender, EventArgs e)
{
System.Diagnostics.Process CC2650 = new System.Diagnostics.Process();
CC2650.StartInfo.FileName = #"D:\Projects\Test_Fixture\Test_Fixture_Visual_Studio\SmartRF Tools\Flash Programmer 2\bin\srfprog.exe";
CC2650.StartInfo.Arguments = "srfprog -t soc(COM84,CC2650) -e -p -v -f c:\test.bin"; //argument
CC2650.StartInfo.UseShellExecute = false;
CC2650.StartInfo.RedirectStandardOutput = true;
CC2650.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
CC2650.StartInfo.CreateNoWindow = false; //not diplay a windows
CC2650.Start();
string output = CC2650.StandardOutput.ReadToEnd(); //The output result
CC2650.WaitForExit();
}
In this test I`m using the fixed COM port. Later I will select the port.
Why my software is falling and doesn`t load the firmware?
Thank you for your attention and time.
Your code seems to be doubling up on srfprog by including it in the arguments. Filename defines the executable and Arguments should just be the stuff that comes after the Filename.
CC2650.StartInfo.Arguments = "-t soc(COM84,CC2650) -e -p -v -f c:\test.bin";
As mentioned before you don't need to pass the program name again in the arguments. To inspect what is happening please use code below. It will read the output and the errors in an async approach so we can analyse the output while the srfprog.exe is running.
I don't have any C# compiler here so I could not test this code before writing here, maybe you will have to change something to make it work. Please try it and let my know what will be printed in your Visual Studio output console.
// Add "using System.Diagnostics;"
private void button2_Click(object sender, EventArgs e)
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = #"D:\Projects\Test_Fixture\Test_Fixture_Visual_Studio\SmartRF Tools\Flash Programmer 2\bin\srfprog.exe";
startInfo.Arguments = "-t soc(COM84,CC2650) -e -p -v -f c:\test.bin";
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
Process process = new Process();
process.StartInfo = startInfo;
process.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);
process.ErrorDataReceived += new DataReceivedEventHandler(OutputHandler);
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
}
static void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
Console.WriteLine(outLine.Data);
}

C# Process removes quoted arguments

The command I'm trying to execute is
"C:\Program Files (x86)\MyAPP\solr-6.2.0\bin\solr" start -f -c -z "10.195.42.93:2181,10.195.42.92:2181" -h 10.195.42.92
And this works just fine on the command Line.
I'm trying to execute this as C# process.
NOTE: Below code works fine if i remove the quotes surrounding IPList
var IPList="10.195.42.93:2181,10.195.42.92:2181";
var hostIP="10.195.42.92"
string command = #"/c ""C:\Program Files (x86)\MyApp\solr-6.2.0\bin\solr"" start -f -c -z """ + IPList + #""" -h " + hostIP;
Process process = new Process();
log.Info("Starting " + command);
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = command;
process.StartInfo = startInfo;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.OutputDataReceived += (s, e) => log.Info(e.Data);
process.ErrorDataReceived += (s, e) => log.Info(e.Data);
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
This throws error :
'C:\Program' is not recognized as an internal or external command,...
I have looked at the similar issue posted Here and tried the /s option but no heed.
What am i missing here ?
As the error says, it is trying to execute C:\Program which basically means something is wrong with the way you are escaping quotes. May be try to escape " using - \"
You're asking cmd.exe to run the command C:\Program Files (x86)\MyApp\solr-6.2.0\bin\solr. It will not run "C:\Program Files (x86)\MyApp\solr-6.2.0\bin\solr" because the quotes are consumed by the invocation of cmd.exe.
I do not know the proper way to fix this. You probably need to add escaped quotes somehow.
Enclosing the command with "(quotes) after /c solves the issue.
Example :
"/c ""c:\prog files\xyz\solr" start -c -z "blah,blah,blah" -h
IP "
Basically the command that is getting executed is
> cmd.exe /c "C:\Program Files (x86)\MyAPP\solr-6.2.0\bin\solr" start -f -c -z "10.195.42.93:2181,10.195.42.92:2181" -h 10.195.42.92
This command fails, and this has nothing to do with c# process api or .net.

Kill Process in ffmpeg in c#

I'm using Process class to execute commands in ffmpeg like this:
string command = "/C ffmpeg -re -i test.mp4 -f mpegts udp://127.0.0.1:" + port.Text;
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.StartInfo.Arguments = command;
process.Start();
this code streams video to network, but I want to stop streaming when I click on button
I used process.kill() but the process still streaming even if I closed application
How can I stop process in background or send ctrl+c to it ?
The leading "/C" indicates that you start it via cmd.exe?
In that case process corresponds to cmd which in turn starts ffmpeg. Thus killing cmd doesn't kill ffmpeg.
string command = "-re -i test.mp4 -f mpegts udp://127.0.0.1:" + port.Text;
process.StartInfo.FileName ="ffmpeg";
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.StartInfo.Arguments = command;
process.Start();
process.Kill(); should work then.
So I was going through the same trouble of starting and stopping ffmpeg process in my selenium Nunit test. After bit of struggle I was able to create a simple solution. Sending as "q" a input to the process window of ffmpeg gracefully stops the process and the video recording is not corrupt as well.
here is my c# code to start the ffmpeg and stop it after execution.
Create a bat file to start your ffmpeg (you will be calling this batfile from your c# code)
In you selenium test , create a recording class and 2 methods to start and stop the recording(in my case I was starting the bat file before all test as in calling the executeScreenRecordingBatFile method in onetimesetup attribute to start the recording and calling the StopScreenRecording method in onetimeteardown ) Sample code below.
using System.Diagnostics;
using System.IO;
namespace FunctionalTests
{
public class Recording
{
public static Process process;
public static void executeScreenRecordingBatFile()
{
try
{
process = new Process();
process.StartInfo.FileName = #"C:\Program Files (x86)\StartScreenRecording.bat";
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardInput = true;// this required to send input to the current process window.
bool started = process.Start();
if (started==true)
{
Console.WriteLine("Bat file started");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace.ToString());
throw;
}
}
public static void StopScreenRecording()
{
StreamWriter myStreamWriter = process.StandardInput; // this required to send StandardInput stream, nothing fancy
myStreamWriter.WriteLine("q"); //this will send q as an input to the ffmpeg process window making it stop , please cross check in task manager once if the ffmpeg is still running or closed.
}
}
}
I created a method to kill ffmpeg process.
private void KillAllFFMPEG()
{
Process killFfmpeg = new Process();
ProcessStartInfo taskkillStartInfo = new ProcessStartInfo
{
FileName = "taskkill",
Arguments = "/F /IM ffmpeg.exe",
UseShellExecute = false,
CreateNoWindow = true
};
killFfmpeg.StartInfo = taskkillStartInfo;
killFfmpeg.Start();
}
Just call it wherever you want.
UPDATE 1
In order to kill just one instance of the FFMPEG process, we need to get it's PID first. When you define your ffmpeg process for streaming, define it in the global scope and use following command to get the PID after it is initialized.
int myProcessId = FfmpegProcess.Id;
Then call the following
private void KillFFMPEGByPID(int PID)
{
Process killFfmpeg = new Process();
ProcessStartInfo taskkillStartInfo = new ProcessStartInfo
{
FileName = "taskkill",
Arguments = "/PID " + Convert.ToString(PID) + " /T",
UseShellExecute = false,
CreateNoWindow = true
};
killFfmpeg.StartInfo = taskkillStartInfo;
killFfmpeg.Start();
}
This will kill only the process with the given PID. /T flag at the end of the argument determines that whole process tree will be killed.
Cheers

Cannot see the results of command line

Previously somebody has asked how to run a command line command in C# from visual studio and the beneath was the answer.
I tried the same intended to call a tool called cccc which can run on command line. But when I run the beneath code I do not get any results and nothing shows wrong.
Stating generally how can we run the same commands from C# as it was in command line and get the same results. Say I call a program (it could be any program that is able to run on command line, for instance, cccc, ccm, and so on) on command line and get some results. How to call the command line and give the arguments so it will call in its turn the cccc or whatever and do the same thing as it was without C#.
string strCmdText;
strCmdText = "/C d: cd D:\\Exercises\\npp52\\PowerEditor\\src && dir /s /b | cccc - --outdir=d:\\myfolder";
System.Diagnostics.Process.Start("CMD.exe", strCmdText);
Add 'pause' to the end of your command:
string strCmdText;
strCmdText = "/C d: cd D:\\Exercises\\npp52\\PowerEditor\\src && dir /s /b | cccc - --outdir=d:\\myfolder & pause";
System.Diagnostics.Process.Start("CMD.exe", strCmdText);
or redirect console standard output to a stream.
Here need more magic with OutputDataReceived handler
void Main()
{
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName="cmd.exe";
proc.StartInfo.Arguments = "/c ping 127.0.0.1";
proc.StartInfo.UseShellExecute = false;
proc.OutputDataReceived += new DataReceivedEventHandler(SortOutputHandler);
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
proc.BeginOutputReadLine();
proc.WaitForExit();
proc.Close();
}
private void SortOutputHandler(object sendingProcess,
DataReceivedEventArgs outLine)
{
if (!String.IsNullOrEmpty(outLine.Data))
{
// Do what You need with out
Console.WriteLine(outLine.Data);
}
}
Instead of trying to put everything inside a string you could take advantage of the ProcessStartInfo class to better define your arguments
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "CMD.EXE";
psi.WorkingDirectory = "D:\\Exercises\\npp52\\PowerEditor\\src ";
psi.Arguments = "/C dir /s /b | cccc - --outdir=d:\\myfolder"";
psi.WindowStyle = ProcessWindowStyle.Normal;
Process.Start(psi);
Also with the command window open you could see if there are syntax errors in your command
Another problem is that you are not using RedirectStandardOutput, so output is discarded. Take a look at this answer.

Run Command Prompt Commands

Is there any way to run command prompt commands from within a C# application? If so how would I do the following:
copy /b Image1.jpg + Archive.rar Image2.jpg
This basically embeds an RAR file within JPG image. I was just wondering if there was a way to do this automatically in C#.
this is all you have to do run shell commands from C#
string strCmdText;
strCmdText= "/C copy /b Image1.jpg + Archive.rar Image2.jpg";
System.Diagnostics.Process.Start("CMD.exe",strCmdText);
EDIT:
This is to hide the cmd window.
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/C copy /b Image1.jpg + Archive.rar Image2.jpg";
process.StartInfo = startInfo;
process.Start();
EDIT 2:
It is important that the argument begins with /C, otherwise it won't work. As #scott-ferguson said: /C carries out the command specified by the string and then terminates.
Tried RameshVel's solution but I could not pass arguments in my console application. If anyone experiences the same problem here is a solution:
using System.Diagnostics;
Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.UseShellExecute = false;
cmd.Start();
cmd.StandardInput.WriteLine("echo Oscar");
cmd.StandardInput.Flush();
cmd.StandardInput.Close();
cmd.WaitForExit();
Console.WriteLine(cmd.StandardOutput.ReadToEnd());
var proc1 = new ProcessStartInfo();
string anyCommand;
proc1.UseShellExecute = true;
proc1.WorkingDirectory = #"C:\Windows\System32";
proc1.FileName = #"C:\Windows\System32\cmd.exe";
proc1.Verb = "runas";
proc1.Arguments = "/c "+anyCommand;
proc1.WindowStyle = ProcessWindowStyle.Hidden;
Process.Start(proc1);
None of the above answers helped for some reason, it seems like they sweep errors under the rug and make troubleshooting one's command difficult. So I ended up going with something like this, maybe it will help someone else:
var proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = #"C:\Program Files\Microsoft Visual Studio 14.0\Common7\IDE\tf.exe",
Arguments = "checkout AndroidManifest.xml",
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true,
WorkingDirectory = #"C:\MyAndroidApp\"
}
};
proc.Start();
Though technically this doesn't directly answer question posed, it does answer the question of how to do what the original poster wanted to do: combine files. If anything, this is a post to help newbies understand what Instance Hunter and Konstantin are talking about.
This is the method I use to combine files (in this case a jpg and a zip). Note that I create a buffer that gets filled with the content of the zip file (in small chunks rather than in one big read operation), and then the buffer gets written to the back of the jpg file until the end of the zip file is reached:
private void CombineFiles(string jpgFileName, string zipFileName)
{
using (Stream original = new FileStream(jpgFileName, FileMode.Append))
{
using (Stream extra = new FileStream(zipFileName, FileMode.Open, FileAccess.Read))
{
var buffer = new byte[32 * 1024];
int blockSize;
while ((blockSize = extra.Read(buffer, 0, buffer.Length)) > 0)
{
original.Write(buffer, 0, blockSize);
}
}
}
}
if you want to run the command in async mode - and print the results. you can you this class:
public static class ExecuteCmd
{
/// <summary>
/// Executes a shell command synchronously.
/// </summary>
/// <param name="command">string command</param>
/// <returns>string, as output of the command.</returns>
public static void ExecuteCommandSync(object command)
{
try
{
// create the ProcessStartInfo using "cmd" as the program to be run, and "/c " as the parameters.
// Incidentally, /c tells cmd that we want it to execute the command that follows, and then exit.
System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
// The following commands are needed to redirect the standard output.
//This means that it will be redirected to the Process.StandardOutput StreamReader.
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
// Do not create the black window.
procStartInfo.CreateNoWindow = true;
// Now we create a process, assign its ProcessStartInfo and start it
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
// Get the output into a string
string result = proc.StandardOutput.ReadToEnd();
// Display the command output.
Console.WriteLine(result);
}
catch (Exception objException)
{
// Log the exception
Console.WriteLine("ExecuteCommandSync failed" + objException.Message);
}
}
/// <summary>
/// Execute the command Asynchronously.
/// </summary>
/// <param name="command">string command.</param>
public static void ExecuteCommandAsync(string command)
{
try
{
//Asynchronously start the Thread to process the Execute command request.
Thread objThread = new Thread(new ParameterizedThreadStart(ExecuteCommandSync));
//Make the thread as background thread.
objThread.IsBackground = true;
//Set the Priority of the thread.
objThread.Priority = ThreadPriority.AboveNormal;
//Start the thread.
objThread.Start(command);
}
catch (ThreadStartException )
{
// Log the exception
}
catch (ThreadAbortException )
{
// Log the exception
}
catch (Exception )
{
// Log the exception
}
}
}
if you want to keep the cmd window open or want to use it in winform/wpf then use it like this
string strCmdText;
//For Testing
strCmdText= "/K ipconfig";
System.Diagnostics.Process.Start("CMD.exe",strCmdText);
/K
Will keep the cmd window open
Yes, there is (see link in Matt Hamilton's comment), but it would be easier and better to use .NET's IO classes. You can use File.ReadAllBytes to read the files and then File.WriteAllBytes to write the "embedded" version.
with a reference to Microsoft.VisualBasic
Interaction.Shell("copy /b Image1.jpg + Archive.rar Image2.jpg", AppWinStyle.Hide);
This can also be done by P/Invoking the C standard library's system function.
using System.Runtime.InteropServices;
[DllImport("msvcrt.dll")]
public static extern int system(string format);
system("copy Test.txt Test2.txt");
Output:
1 file(s) copied.
Here is little simple and less code version. It will hide the console window too-
System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = "/C copy /b Image1.jpg + Archive.rar Image2.jpg";
process.Start();
I have the following method, which I use to run the command prompt commands from C#
In first parameter pass the command you want to run
public static string RunCommand(string arguments, bool readOutput)
{
var output = string.Empty;
try
{
var startInfo = new ProcessStartInfo
{
Verb = "runas",
FileName = "cmd.exe",
Arguments = "/C "+arguments,
WindowStyle = ProcessWindowStyle.Hidden,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = false
};
var proc = Process.Start(startInfo);
if (readOutput)
{
output = proc.StandardOutput.ReadToEnd();
}
proc.WaitForExit(60000);
return output;
}
catch (Exception)
{
return output;
}
}
You can achieve this by using the following method (as mentioned in other answers):
strCmdText = "'/C some command";
Process.Start("CMD.exe", strCmdText);
When I tried the methods listed above I found that my custom command did not work using the syntax of some of the answers above.
I found out more complex commands need to be encapsulated in quotes to work:
string strCmdText;
strCmdText = "'/C cd " + path + " && composer update && composer install -o'";
Process.Start("CMD.exe", strCmdText);
you can use simply write the code in a .bat format extension ,the code of the batch file :
c:/ copy /b Image1.jpg + Archive.rar Image2.jpg
use this c# code :
Process.Start("file_name.bat")
You can use RunProcessAsTask pacakge and run your process async and easily like this:
var processResults = await ProcessEx.RunAsync("git.exe", "pull");
//get process result
foreach (var output in processResults.StandardOutput)
{
Console.WriteLine("Output line: " + output);
}
This may be a bit of a read so im sorry in advance. And this is my tried and tested way of doing this, there may be a simpler way but this is from me throwing code at a wall and seeing what stuck
If it can be done with a batch file then the maybe over complicated work around is have c# write a .bat file and run it. If you want user input you could place the input into a variable and have c# write it into the file. it will take trial and error with this way because its like controlling a puppet with another puppet.
here is an example, In this case the function is for a push button in windows forum app that clears the print queue.
using System.IO;
using System;
public static void ClearPrintQueue()
{
//this is the path the document or in our case batch file will be placed
string docPath =
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
//this is the path process.start usues
string path1 = docPath + "\\Test.bat";
// these are the batch commands
// remember its "", the comma separates the lines
string[] lines =
{
"#echo off",
"net stop spooler",
"del %systemroot%\\System32\\spool\\Printers\\* /Q",
"net start spooler",
//this deletes the file
"del \"%~f0\"" //do not put a comma on the last line
};
//this writes the string to the file
using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "test.bat")))
{
//This writes the file line by line
foreach (string line in lines)
outputFile.WriteLine(line);
}
System.Diagnostics.Process.Start(path1);
}
IF you want user input then you could try something like this.
This is for setting the computer IP as static but asking the user what the IP, gateway, and dns server is.
you will need this for it to work
public static void SetIPStatic()
{
//These open pop up boxes which ask for user input
string STATIC = Microsoft.VisualBasic.Interaction.InputBox("Whats the static IP?", "", "", 100, 100);
string SUBNET = Microsoft.VisualBasic.Interaction.InputBox("Whats the Subnet?(Press enter for default)", "255.255.255.0", "", 100, 100);
string DEFAULTGATEWAY = Microsoft.VisualBasic.Interaction.InputBox("Whats the Default gateway?", "", "", 100, 100);
string DNS = Microsoft.VisualBasic.Interaction.InputBox("Whats the DNS server IP?(Input required, 8.8.4.4 has already been set as secondary)", "", "", 100, 100);
//this is the path the document or in our case batch file will be placed
string docPath =
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
//this is the path process.start usues
string path1 = docPath + "\\Test.bat";
// these are the batch commands
// remember its "", the comma separates the lines
string[] lines =
{
"SETLOCAL EnableDelayedExpansion",
"SET adapterName=",
"FOR /F \"tokens=* delims=:\" %%a IN ('IPCONFIG ^| FIND /I \"ETHERNET ADAPTER\"') DO (",
"SET adapterName=%%a",
"REM Removes \"Ethernet adapter\" from the front of the adapter name",
"SET adapterName=!adapterName:~17!",
"REM Removes the colon from the end of the adapter name",
"SET adapterName=!adapterName:~0,-1!",
//the variables that were set before are used here
"netsh interface ipv4 set address name=\"!adapterName!\" static " + STATIC + " " + STATIC + " " + DEFAULTGATEWAY,
"netsh interface ipv4 set dns name=\"!adapterName!\" static " + DNS + " primary",
"netsh interface ipv4 add dns name=\"!adapterName!\" 8.8.4.4 index=2",
")",
"ipconfig /flushdns",
"ipconfig /registerdns",
":EOF",
"DEL \"%~f0\"",
""
};
//this writes the string to the file
using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "test.bat")))
{
//This writes the file line by line
foreach (string line in lines)
outputFile.WriteLine(line);
}
System.Diagnostics.Process.Start(path1);
}
Like I said. It may be a little overcomplicated but it never fails unless I write the batch commands wrong.

Categories

Resources