Close a batch file ran by c# - c#

I have a simpel program that runs a vulnerability scan on the given port and host. Now I have to find a way to close the batch file that is run from my c# form.
I have to be able to close the batch file from a button, even when its not finished yet. And i have no clue, nor did i find a way somewhere.
EDIT: Added more code, but still given the error "process doesn't exist in current context"
private void button10_Click(object sender, EventArgs e)
{
if (button10.Text == "Scan")
{
int port = (int)numericUpDown2.Value;
string path = Directory.GetCurrentDirectory();
string strCommand = path + "/SystemFiles/nikto/nikto.bat";
string host = textBox5.Text;
Console.WriteLine(strCommand);
richTextBox5.Text += "Starting Nikto Vulnerability Scan On " + host + " On Port " + port + System.Environment.NewLine;
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.FileName = strCommand;
startInfo.Arguments = "-h " + host + " -port " + port + textBox6.Text;
process.StartInfo = startInfo;
process.Start();
richTextBox5.Text += "Vulnerability Scan Started On " + host + " On Port " + port + System.Environment.NewLine;
button10.Text = "Cancel";
}
else
{
process.Kill();
button10.Text = "Scan";
}
}

You may use the method kill in the process object
process.Kill()

Here is the full answer.
public partial class Form1 : Form
{
private System.Diagnostics.Process _process;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (_process == null || _process.HasExited)
{
_process = new Process();
}
else
{
_process.Kill();
_process = null;
button10.Text = "Scan";
return;
}
int port = (int)numericUpDown2.Value;
string path = Directory.GetCurrentDirectory();
string strCommand = path + "/SystemFiles/nikto/nikto.bat";
string host = textBox5.Text;
Console.WriteLine(strCommand);
richTextBox5.Text += "Starting Nikto Vulnerability Scan On " + host + " On Port " + port + System.Environment.NewLine;
ProcessStartInfo startInfo = new ProcessStartInfo
{
FileName = strCommand,
Arguments = "-h " + host + " -port " + port + textBox6.Text
};
_process.StartInfo = startInfo;
_process.Start();
richTextBox5.Text += "Vulnerability Scan Started On " + host + " On Port " + port + System.Environment.NewLine;
button10.Text = "Cancel";
}
}

Related

Code after Process.Start() call not running, but working when debugging C#

Here is the function that is calling Process.Start().
I am simply opening two folders in WinMerge. This part works correctly and this application pops up. None of the code written after this runs though. However, when I place a breakpoint on p.Dispose() or p.Start() and press continue, everything afterwards works correctly.
private void openWinMerge(string leftFile, string rightFile)
{
string args = "/C /f *.xml " + leftFile + " " + rightFile;
Process p = new Process();
p.StartInfo.FileName = "C:\\Program Files (x86)\\WinMerge\\WinMergeU.exe";
p.StartInfo.Arguments = args;
p.StartInfo.CreateNoWindow = true;
if (p.Start())
{
p.Dispose();
return;
}
}
This is where I call the function calling Process.Start(). None of the code below openWinMerge() runs.
private void btnStart_Click(object sender, EventArgs e)
{
if (txtSerial.Text.Length == 9)
{
PO.Number = txtSerial.Text.ToUpper();
PO.SerialSearch = true;
if (PO.Search())
{
txtPO.Text = PO.Field.ProductionOrderNumber;
search();
createFolders();
copyDefaultFiles();
copyBackupFiles();
openWinMerge("\"" + Path.Combine(path, "INITIAL") + "\"", "\"" + Path.Combine(path, "Default") + "\"");
copyFinalXML();
return;
}
MessageBox.Show("Invalid Serial");
} else if (txtPO.Text.Length == 12)
{
PO.Number = txtPO.Text.ToUpper();
if (PO.Search())
{
txtSerial.Text = PO.Field.SerialNumber;
search();
createFolders();
copyDefaultFiles();
copyBackupFiles();
openWinMerge("\"" + Path.Combine(path, "INITIAL") + "\"", "\"" + Path.Combine(path, "Default") + "\"");
copyFinalXML();
return;
}
MessageBox.Show("Invalid PO or Missing Serial");
} else
{
MessageBox.Show("Please Enter either Serial or PO of Analyzer");
}
}
Update:
I wrote some other code below openWinMerge() and it runs, so my issue is in copyFinalXML()
Here is the code for that
private void copyFinalXML()
{
try
{
string[] files = Directory.GetFiles(Path.Combine(path,"INITIAL"));
Task.Delay(200);
foreach (string file in files)
{
// Will not overwrite if the destination file already exists.
string[] folders = file.Split('\\');
string filename = folders[folders.Length - 1];
if (filename.Equals("config.xml") || filename.Equals("service.xml") || filename.Equals("system.xml"))
{
string d = Path.Combine(Path.Combine(path, "FINAL"), filename);
File.Copy(file, d);
Task.Delay(500);
openNotePad(d);
}
}
}
// Catch exception if the file was already copied.
catch (IOException copyError)
{
MessageBox.Show(copyError.Message);
}
}
private void openNotePad(string filename)
{
//Process.Start("C:\\Program Files(x86)\\Notepad++\\notepad++.exe", "\"" + filename + "\"");
Process.Start(#"notepad++.exe", "\"" + filename + "\"");
return;
}
Add p.WaitForExit(); to your code just before the code you want to execute after it finishes running the process.

Connect to VPN xamarin android

Hello I am using this code to connect vpn with c# my code can connect and disconnect and create vpn and it working fine but i want use it in xamarin android i do search google but No result
private static string FolderPath => string.Concat(Directory.GetCurrentDirectory(),
"\\VPN");
private void btnConnect_Click(object sender, EventArgs e)
{
if (!Directory.Exists(FolderPath))
Directory.CreateDirectory(FolderPath);
var sb = new StringBuilder();
sb.AppendLine("[VPN]");
sb.AppendLine("MEDIA=rastapi");
sb.AppendLine("Port=VPN2-0");
sb.AppendLine("Device=WAN Miniport (IKEv2)");
sb.AppendLine("DEVICE=vpn");
sb.AppendLine("PhoneNumber=" + txtHost.Text);
File.WriteAllText(FolderPath + "\\VpnConnection.pbk", sb.ToString());
sb = new StringBuilder();
sb.AppendLine("rasdial \"VPN\" " + txtUsrname.Text + " " + txtPassword.Text + " /phonebook:\"" + FolderPath +
"\\VpnConnection.pbk\"");
File.WriteAllText(FolderPath + "\\VpnConnection.bat", sb.ToString());
var newProcess = new Process
{
StartInfo =
{
FileName = FolderPath + "\\VpnConnection.bat",
WindowStyle = ProcessWindowStyle.Normal
}
};
newProcess.Start();
newProcess.WaitForExit();
btnConnect.Enabled = false;
btnDisconnect.Enabled = true;
}
private void btnDisconnect_Click(object sender, EventArgs e)
{
File.WriteAllText(FolderPath + "\\VpnDisconnect.bat", "rasdial /d");
var newProcess = new Process
{
StartInfo =
{
FileName = FolderPath + "\\VpnDisconnect.bat",
WindowStyle = ProcessWindowStyle.Normal
}
};
newProcess.Start();
newProcess.WaitForExit();
btnConnect.Enabled = true;
btnDisconnect.Enabled = false;
}
or I want convert it to xamarin android and
connect or disconnect sorry for my english

Process Wait For Exit not work

I'm using the below code to download from youtube using youtube-dl python script.
string pythonPath = #"C:\Python35\python.exe";
string ydl = #"C:\Y\ydl\youtube-dl";
string tempLocation = Server.MapPath("/ydl/");
string Output = "";
string Error = "";
int numOutputLines = 0;
int numErrorLines = 0;
using (Process process = new Process())
{
process.EnableRaisingEvents = true;
process.StartInfo.ErrorDialog = false;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.FileName = pythonPath;
process.StartInfo.WorkingDirectory = tempLocation;
process.StartInfo.Arguments = ydl + " --output test.mp4 --force-ipv4 -f bestvideo[ext=mp4]+bestaudio[ext=m4a] \"" + Url + "\"";
process.StartInfo.Verb = "runas";
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
StringBuilder output = new StringBuilder();
StringBuilder error = new StringBuilder();
using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))
using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
{
process.OutputDataReceived += (sender, e) =>
{
if (e.Data == null)
{
outputWaitHandle.Set();
}
else
{
numOutputLines++;
this.Context.Response.Write(Environment.NewLine + "[" + numOutputLines.ToString() + "] - " + e.Data);
output.AppendLine("[" + numOutputLines.ToString() + "] - " + e.Data);
}
};
process.ErrorDataReceived += (sender, e) =>
{
if (e.Data == null)
{
errorWaitHandle.Set();
}
else
{
numErrorLines++;
this.Context.Response.Write(Environment.NewLine + "[" + numErrorLines.ToString() + "] - " + e.Data);
error.AppendLine("[" + numErrorLines.ToString() + "] - " + e.Data);
}
};
//process.Exited += (s, a) =>
//{
// process.Close();
//};
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
//process.WaitForExit();
Process[] curProcess = Process.GetProcessesByName("youtube-dl");
Process youtubeProcess = curProcess.FirstOrDefault();
while (!youtubeProcess.HasExited)
{
Thread.Sleep(100);
}
Output = output.ToString();
Error = error.ToString();
process.Close();
}
}
I used the proccess in this way because I want to have the percentage of youtube-dl script for showing in my client side progress bar.
But there are some problems and it's that WaitForExit is not working. I read from other topics that this issue is related to wait in process not working for child process(I mean in my way, the wait for exit works for python not for youtube-dl script)
What should I do?
Since you are interested in a child process maybe you an try to poll on the youtube process by using the method:
Process.GetProcessesByName(string processName);
Something like this:
Process[] curProcess = Process.GetProcessesByName("your youtube process name");
Process youtubeProcess = curProcess.FirstOrDefault(); // Get here the right process instance
while (!youtubeProcess.HasExited)
{
Thread.Sleep(100);
}

Capturing process output via OutputDataReceived event

I'm trying to capture process output in "realtime" (while it's running). The code I use is rather simple (see below). For some strange reason the OutputDataReceived event is never called. Why?
private void button2_Click(object sender, EventArgs e)
{
// Setup the process start info
var processStartInfo = new ProcessStartInfo("ping.exe", "-t -n 3 192.168.100.1")
{
UseShellExecute = false,
RedirectStandardOutput = true
};
// Setup the process
mProcess = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true };
// Register event
mProcess.OutputDataReceived += OnOutputDataReceived;
// Start process
mProcess.Start();
mProcess.WaitForExit();
}
void OnOutputDataReceived(object sender, DataReceivedEventArgs e)
{
//Never gets called...
}
You need to call
mProcess.BeginOutputReadLine();
BeginOutputReadLine - "Begins asynchronous read operations on the redirected StandardOutput stream of the application."
void ExecuteCommand(string cmdpath, string cmdargs)
{
string command = cmdpath + " " + cmdargs;
tabc_results.SelectTab(1);
DoConsole("\r\nCmd>> " + command + "\r\n");
var processInfo = new System.Diagnostics.ProcessStartInfo("cmd.exe", "/c " + command);
processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = false;
processInfo.RedirectStandardError = true;
processInfo.RedirectStandardOutput = true;
var process = System.Diagnostics.Process.Start(processInfo);
process.OutputDataReceived += (
object sender, System.Diagnostics.DataReceivedEventArgs e
) => DoConsole("stdout>> " + e.Data + "\r\n");
//Console.WriteLine("output>>" + e.Data);
process.BeginOutputReadLine();
process.ErrorDataReceived += (
object sender, System.Diagnostics.DataReceivedEventArgs e
) =>DoConsole("stderr>> " + e.Data + "\r\n");
//Console.WriteLine("error>>" + e.Data);
process.BeginErrorReadLine();
process.WaitForExit();
DoConsole("retcode>> " + process.ExitCode.ToString() + "\r\n");
//Console.WriteLine("ExitCode: {0}", process.ExitCode);
process.Close();
}

convert all video files to flv using asp.net with c# by using ffmpeg.exe

This is my code below . Its not working to take image from the given video and not converting any kind of video to flv format.Its converting but after converting that flv and thumb images files is not save in the temp(store images) data(store convert flv)folder.That folder is empty.
i am debugging code but it is not giving any kind of exception and error.
Kindly debug my code.Awaiting for ur reply experts...
in Default2.aspx page
a file upload control and save button is there.
Default2.aspx.cs page
protected void Page_Load(object sender, EventArgs e)
{
string ffmpegPath = "";
string tempLocation = "";
string mediaOutPath = "";
string thumbOutPath = "";
string currentFile = "";
ffmpegPath = Server.MapPath("~/ffmpeg/ffmpeg.exe");
tempLocation = Server.MapPath("~/VideoGallery/temp/");
mediaOutPath = Server.MapPath("~/VideoGallery/data/");
thumbOutPath = Server.MapPath("~/VideoGallery/thumb/");
}
protected void Submit1_ServerClick(object sender, System.EventArgs e)
{
if ((File1.PostedFile != null) && (File1.PostedFile.ContentLength > 0))
{
currentFile = System.IO.Path.GetFileName(File1.PostedFile.FileName);
try
{
Convert(tempLocation + currentFile, mediaOutPath + currentFile, thumbOutPath +
currentFile);
File1.PostedFile.SaveAs(tempLocation + currentFile);
Response.Write("The file has been uploaded.");
}
catch (Exception ex)
{
Response.Write("Error: " + ex.Message);
}
}
else
{
Response.Write("Please select a file to upload.");
}
}
protected void Convert(string fileIn, string fileOut, string thumbOut)
{
try
{
//convert flv
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.EnableRaisingEvents = false;
proc.StartInfo.FileName = ffmpegPath;
proc.StartInfo.Arguments = "-i " + fileIn +
" -ar 22050 -ab 32 -f flv -s 320×240 -aspect 4:3 -y " + fileOut.Split('.')[0] +
".flv";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
proc.WaitForExit();
//convert img
proc.StartInfo.Arguments = "-i " + fileIn +
" -an -ss 00:00:03 -s 120×90 -vframes 1 -f mjpeg " + thumbOut.Split('.')[0] +
".jpg";
proc.Start();
proc.WaitForExit();
proc.Close();
}
catch (Exception ex)
{
Response.Write("Error: " + ex.Message);
}
}
}

Categories

Resources