Run a Process silently in background without any window - c#

I want to run NETSH command silently (with no window).
I wrote this code but it does not work.
public static bool ExecuteApplication(string Address, string workingDir, string arguments, bool showWindow)
{
Process proc = new Process();
proc.StartInfo.FileName = Address;
proc.StartInfo.WorkingDirectory = workingDir;
proc.StartInfo.Arguments = arguments;
proc.StartInfo.CreateNoWindow = showWindow;
return proc.Start();
}
string cmd= "interface set interface name=\"" + InterfaceName+"\" admin=enable";
ExecuteApplication("netsh.exe","",cmd, false);

This is how I do it in a project of mine:
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "netsh";
psi.UseShellExecute = false;
psi.RedirectStandardError = true;
psi.RedirectStandardOutput = true;
psi.Arguments = "SOME_ARGUMENTS";
Process proc = Process.Start(psi);
proc.WaitForExit();
string errorOutput = proc.StandardError.ReadToEnd();
string standardOutput = proc.StandardOutput.ReadToEnd();
if (proc.ExitCode != 0)
throw new Exception("netsh exit code: " + proc.ExitCode.ToString() + " " + (!string.IsNullOrEmpty(errorOutput) ? " " + errorOutput : "") + " " + (!string.IsNullOrEmpty(standardOutput) ? " " + standardOutput : ""));
It also accounts for the outputs of the command.

Make user shell execution false
proc.StartInfo.UseShellExecute = false;
and pass true in showWindow parameter
ExecuteApplication("netsh.exe","",cmd, true);

Related

Create a forms app to restart a remote PC

I just need to create a tool to restart a specific windows device in our city offices. which will always in 192.168.cityID.33 I have found a way to detect the citycode portion of the IP and to add 33 to it in GetIPMethod.
thee mentioned device have different set of username and password im having issues passing the restart command to the cmd
PS: I'm not a full time developer i'm just a network admin who tries to reduce my daily work load :)
Thanks in advance
public void Command1()
{
String IP = GetIPAddress().ToString();
string NewIP = IP.Substring(0, IP.LastIndexOf("."));
string TOPIP = NewIP + ".33";
Process process = new Process();
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.UseShellExecute = false;
process.StandardInput.WriteLine("NET USE \\" + TOPIP + "\receiver /USER:GenusDS G3nu5DS");
process.StandardInput.WriteLine("shutdown /m \\" + TOPIP + " /r /f -t 00");
process.Start();
process.StandardInput.Flush();
process.Close();
process.WaitForExit();
Console.WriteLine(process.StandardOutput.ReadToEnd());
Console.ReadKey();
string strCmdText;
strCmdText = "NET USE \\" + TOPIP + "\receiver /USER:GDS G3nS";
System.Diagnostics.Process.Start("CMD.exe",strCmdText);
}
public static IPAddress GetIPAddress()
{
IPAddress ip = Dns.GetHostAddresses(Dns.GetHostName()).Where(address =>
address.AddressFamily == AddressFamily.InterNetwork).First();
return ip;
}
I normally do something similar to below:
Process process = new Process();
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/C net use \\[My IP] [My Password] /USER:[My Username]";
process.StartInfo = startInfo;
Process.Start(startInfo);
And this question shows how to run multiple commands in one process.
Hope that helps.
var proc1 = new ProcessStartInfo();
string Command;
proc1.UseShellExecute = true;
Command = "net use " + slash + TOPIP + "\\receiver /user:GenusDS G3nu5DS&shutdown /m " + slash + TOPIP + " /r /f -t 00";
proc1.WorkingDirectory = #"C:\Windows\System32";
proc1.FileName = #"C:\Windows\System32\cmd.exe";
/// as admin = proc1.Verb = "runas";
proc1.Arguments = "/c " + Command;
proc1.WindowStyle = ProcessWindowStyle.Maximized;
Process.Start(proc1);

Process is not exiting ffmpeg.exe only for the command which detects the silences from a video

The job of the method ExecuteCommandSync is to detect the silences from a video and return the output as string but when I run this code it never bring the value of proc.HasExited as true. If I forcefully drag the debugger to the line
result =proc.StandardOutput.ReadToEnd()
then it never exit the ffmpeg.exe so as a result control never returns back.
Although the same method is working fine for a different command like creating an audio file from a video. In this case proc.HasExited also returns false but it also generates the audio file successfully.
public static string ExecuteCommandSync(string fileName, int timeoutMilliseconds)
{
string result = String.Empty;
string workingDirectory = Directory.GetCurrentDirectory();
try
{
string command = string.Format("ffmpeg -i {0} -af silencedetect=noise=-20dB:d=0.2 -f null -", "\"" + fileName + "\"");
System.Diagnostics.ProcessStartInfo procStartInfo =
new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
procStartInfo.WorkingDirectory = workingDirectory;
procStartInfo.RedirectStandardOutput = true;
procStartInfo.RedirectStandardError = true;
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = false;
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
proc.WaitForExit(timeoutMilliseconds);
// Get the output into a string
if (proc.HasExited)
{
if (!proc.StandardOutput.EndOfStream)
{
result = proc.StandardOutput.ReadToEnd();
}
else if (!proc.StandardError.EndOfStream)
{
result = "Error:: " + proc.StandardError.ReadToEnd();
}
}
}
catch (Exception)
{
throw;
}
return result;
}
So please advice.

ffmpeg ask for intsall

I am trying to create an image/thumbnail from the video stored in local folder.
Here is what I am doing is-
Process p;
ProcessStartInfo info = new ProcessStartInfo();
info.FileName = Server.MapPath("~/FFMPEG/ffmpeg.exe");
info.RedirectStandardOutput = false;
info.CreateNoWindow = false;
info.Arguments = " -i " + videopath + " -vframes 1 " + imagepath + "%d.jpg";
info.UseShellExecute = false;
p = Process.Start(info);
while (!p.HasExited) { Thread.Sleep(10); }
When I execute above code a popup box comes to install ffmpeg.exe
If I install the software, for the next time it asks again.
Am I doing some mistake?
info.CreateNoWindow = true;
info.WindowStyle = ProcessWindowStyle.Hidden;
Below is the code
Process p;
ProcessStartInfo info = new ProcessStartInfo();
info.FileName = Server.MapPath("~/FFMPEG/ffmpeg.exe");
info.RedirectStandardOutput = false;
// below lines will not open the command window
info.CreateNoWindow = true;
info.WindowStyle = ProcessWindowStyle.Hidden;
info.Arguments = " -i " + videopath + " -vframes 1 " + imagepath + "%d.jpg";
info.UseShellExecute = false;
p = Process.Start(info);
while (!p.HasExited) { Thread.Sleep(10); }

C# - I can't dump to a file the output of my process-ish

I've been messing around with C# and in one moment of the code, I need to dump the output of an external .exe into a .txt. I do it by starting cmd.exe and then loading the program, with its attributes plus the > opperator. But now, when I execute the program, the file isn't even created. Meanwhile, if I input the EXACT same code that is passed to cmd in the program:
"o:\steam\steamapps\common\counter-strike global offensive\bin\demoinfogo.exe" "O:\Steam\SteamApps\common\Counter-Strike Global Offensive\csgo\testfile.dem" -gameevents -nofootsteps -deathscsv -nowarmup > "o:\steam\steamapps\common\counter-strike global offensive\demodump.txt"
directly into the Command Prompt, it does get dumped. I've been looking around, and I found A LOT of info, but sadlly nothing has helped me enough so far, so I decided to ask myself.
I attach the chunks of code that I think are relevant to this.
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = true;
startInfo.FileName = "CMD.exe";
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
if (checkBox1.Checked)
{
arguments += " -gameevents";
if (checkBox2.Checked)
{
arguments += " -nofootsteps";
}
if (checkBox3.Checked)
{
arguments += " -extrainfo";
}
}
if (checkBox4.Checked)
{
arguments += " -deathscsv";
if (checkBox5.Checked)
{
arguments += " -nowarmup";
}
}
if (checkBox6.Checked)
{
arguments += " -stringtables";
}
if (checkBox7.Checked)
{
arguments += " -datatables";
}
if (checkBox8.Checked)
{
arguments += " -packetentites";
}
if (checkBox9.Checked)
{
arguments += " -netmessages";
}
if (dumpfilepath == string.Empty)
{
dumpfilepath = getCSGOInstallationPath() + #"\demodump.txt";
}
baseOptions = #"""" + demoinfogopath + #"""" + " " + #"""" + demofilepath + #"""" + arguments;
startInfo.Arguments = baseOptions + " > " + #"""" + dumpfilepath + #"""";
try
{
using (exeProcess = Process.Start(startInfo))
....a bunch of code...
The Process class that you're creating has this useful little property:
Process.StandardOutput
When a Process writes text to its standard stream, that text is normally displayed on the console. By redirecting the StandardOutput stream, you can manipulate or suppress the output of a process. For example, you can filter the text, format it differently, or write the output to both the console and a designated log file.
All you need to do is ensure you're redirecting the StandardOutput to this stream (using the RedirectStandardOutput property in the ProcessStartInfo) and then you can read the output from that stream. Here's the MSDN sample code, slightly abridged:
Process myProcess = new Process();
ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(args[0], "spawn");
myProcessStartInfo.UseShellExecute = false; // important!
myProcessStartInfo.RedirectStandardOutput = true; // also important!
myProcess.StartInfo = myProcessStartInfo;
myProcess.Start();
// Here we're reading the process output's first line:
StreamReader myStreamReader = myProcess.StandardOutput;
string myString = myStreamReader.ReadLine();
Console.WriteLine(myString);
If you look at the help for CMD (access by typing CMD /?) you'll see the following options:
/C Carries out the command specified by string and then terminates
/K Carries out the command specified by string but remains
Without one of those switches, CMD won't interpret the string you provide it as a command to execute.
When I write a short program like the following, it successfully generates a file... but only if I use either the /C or /K options:
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = true;
startInfo.FileName = "CMD.exe";
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
var command = #"echo test > c:\users\myusername\Desktop\test.txt";
var args = "/C " + command;
startInfo.Arguments = args;
using (var process = Process.Start(startInfo)) { }
//Hi you could try this to build your process like this.
public class Launcher
{
public Process CurrentProcess;
public string result = null;
public Process Start()
{
CurrentProcess = new Process
{
StartInfo =
{
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true,
WorkingDirectory = #"C:\",
FileName = Path.Combine(Environment.SystemDirectory, "cmd.exe")
}
};
CurrentProcess.Start();
return CurrentProcess;
}
//Start the process to get the output you want to add to your .txt file:
private void writeOuput()
{
Currentprocess = new process();
Start()
CurrentProcess.StandardInput.WriteLine("Your CMD");
CurrentProcess.StandardInput.Close();
result = CurrentProcess.StandardOutput.ReadLine();
CurrentProcess.StandardOutput.Close()
//Then to put the result in a .txt file:
System.IO.File.WriteAllText (#"C:\path.txt", result);
}
}
}

How to export a registry in c#

I have been trying to export and save registry files to an arbitrary location, the code is running. However, on specifying the path and saving, the function does not work and no registry is exported. There is no error shown either.
private static void Export(string exportPath, string registryPath)
{
string path = "\""+ exportPath + "\"";
string key = "\""+ registryPath + "\"";
// string arguments = "/e" + path + " " + key + "";
Process proc = new Process();
try
{
proc.StartInfo.FileName = "regedit.exe";
proc.StartInfo.UseShellExecute = false;
//proc.StartInfo.Arguments = string.Format("/e", path, key);
proc = Process.Start("regedit.exe", "/e" + path + " "+ key + "");
proc.WaitForExit();
}
catch (Exception)
{
proc.Dispose();
}
}
You need to add a space after the /e parameters so your code will be :
private static void Export(string exportPath, string registryPath)
{
string path = "\""+ exportPath + "\"";
string key = "\""+ registryPath + "\"";
using (Process proc = new Process())
{
try
{
proc.StartInfo.FileName = "regedit.exe";
proc.StartInfo.UseShellExecute = false;
proc = Process.Start("regedit.exe", "/e " + path + " "+ key);
proc.WaitForExit();
}
catch (Exception)
{
// handle exceptions
}
}
}
regedit.exe requires elevated privileges. reg.exe is better choice. It does not require any elevation.
Here's what we do.
void exportRegistry(string strKey, string filepath)
{
try
{
using (Process proc = new Process())
{
proc.StartInfo.FileName = "reg.exe";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.Arguments = "export \"" + strKey + "\" \"" + filepath + "\" /y";
proc.Start();
string stdout = proc.StandardOutput.ReadToEnd();
string stderr = proc.StandardError.ReadToEnd();
proc.WaitForExit();
}
}
catch (Exception ex)
{
// handle exception
}
}

Categories

Resources