I need to write a windows form app, WPF, or console application that should run this from a command prompt:
#echo off
echo test
or
del c:\b.txt
The c# code needs to be on a button but It's not important now.
I tried this:
using System;
using System.Diagnostics;
using System.ComponentModel;
private void button1_Click(object sender, EventArgs e)
{
Process process = new Process();
process.StartInfo.FileName = "cmd.exe";
//process.StartInfo.WorkingDirectory = "c:\temp";
//process.StartInfo.Arguments = "somefile.txt";
Process.Start("cmd", "/dir");
}
but i can't put my CMD code in this ^ code.
I believe what you want is this:
Process p = new Process();
ProcessStartInfo psi = new ProcessStartInfo("cmd.exe");
// add /C for command, a space, then command
psi.Arguments = "/C dir";
p.StartInfo = psi;
p.Start();
The above code allows you to execute the commands directly in the cmd.exe instance. For example, to launch command prompt and see a directory, you assign the Arguments property of the ProcessStartInfo instance to "/C dir", which means execute the command called dir.
Another approach you could use is seen here:
// put your DOS commands in a batch file
ProcessStartInfo startInfo = new ProcessStartInfo("action.bat");
startInfo.UseShellExecute = true;
startInfo.WorkingDirectory = "C:\\dir";
Process.Start(startInfo);
Put the above code in your click event.
Create a batch file with your commands using instructions found at http://www.ehow.com/how_6534808_create-batch-files.html
In my code example, if you name the batch file 'action.bat' and place it in th c:dir folder, everything will work the way you want.
Cheers :)
Related
I'm working on a small C# app that will import a power plan to the user's PC and set it as active.
It working perfectly with a .bat file when the .pow file is in the same folder and I'm running commands:
powercfg -import "%~dp0\Optimized.pow"
powercfg /setactive 62ffd265-db94-4d48-bb7a-183c87641f85
Now, in C# I tried this:
Process cmd = new Process();
cmd.StartInfo.FileName = "powercfg";
cmd.StartInfo.Arguments = "-import \"%~dp0\\Optimized\"";
cmd.StartInfo.Arguments = "powercfg /setactive 62ffd265-db94-4d48-bb7a-183c87641f85";
cmd.Start();
//and this:
private void button1_Click(object sender, EventArgs e)
{
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("powercfg -import \"%~dp0\\Optimized\"");
cmd.StandardInput.WriteLine("powercfg /setactive 6aa8c469-317b-45d9-a69c-f24d53e3aff5");
cmd.StandardInput.Flush();
cmd.StandardInput.Close();
cmd.WaitForExit();
Console.WriteLine(cmd.StandardOutput.ReadToEnd());
}
But the program doesn't see the .pow file in the project folder (I actually tried to put it in each and every folder in the project).
How it can be implemented to let the powercfg see the file?
Any help is much appreciated!
Thanks!
You could try something like this:
var cmd = new Process {StartInfo = {FileName = "powercfg"}};
using (cmd) //This is here because Process implements IDisposable
{
var inputPath = Path.Combine(Environment.CurrentDirectory, "Optimized.pow");
//This hides the resulting popup window
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
//Prepare a guid for this new import
var guidString = Guid.NewGuid().ToString("D"); //Guid without braces
//Import the new power plan
cmd.StartInfo.Arguments = $"-import \"{inputPath}\" {guidString}";
cmd.Start();
//Set the new power plan as active
cmd.StartInfo.Arguments = $"/setactive {guidString}";
cmd.Start();
}
This fixes the Arguments parameter that is being overwritten/used twice, as well as correctly disposes of the cmd variable. Additional lines added to hide the resulting pop-up window, and for generating the Guid upfront and specifying it as part of the command line.
Your first snippet does not work because you're reassigning cmd.StartInfo.Arguments before executing the process. The first assignment is lost when you throw it out in favor of the second assignment.
The first snippet most likely doesn't work because when you set cmd.startInfo.FileName to just a filename with no path, it will search only the directory of your C# app's .exe (likely in project/bin/Debug/). Since the FileName is cmd.exe and there is probably no cmd.exe in your project folder, it can't find anything.
You may also consider setting cmd.StartInfo.WorkingDirectory to an appropriate directory with your .pow file so that your relative paths will resolve correctly.
I'm looking to automate nupkg creation in a c# app. I'm aiming to include nuget.exe in my project and use System.Diagnostics to launch cmd.exe as a process and then pass the required commands, which would be 'cd project\path\here', 'nuget spec something.dll' and 'nuget pack something.nuspec'.
The code I have so far is:
Process p = new Process();
ProcessStartInfo info = new ProcessStartInfo(#"C:\Windows\System32\cmd.exe", #"mkdir testdir");
p.StartInfo = info;
p.Start();
Console.ReadLine();
However, it doesn't even create the testdir, and I've got no idea how to chain those commands. There is a method called WaitForInputIdle on my p Process, but it raises events and I've got no idea how to handle those to be honest.
A perfect solution would also let me read output and input. I've tried using StreamWriter p.StandardInput, but then there's the problem of checking whether a command is finnished and what was the result.
Any help would be much appreciated.
Edit: Success! I've managed to create a directory :)
Here's my code now:
Process p = new Process();
ProcessStartInfo info = new ProcessStartInfo(#"C:\Windows\System32\cmd.exe");
info.RedirectStandardInput = true;
info.UseShellExecute = false;
p.StartInfo = info;
p.Start();
using (StreamWriter sw = p.StandardInput)
{
sw.WriteLine("mkdir lulz");
}
Still no idea how to await for input and follow up with more commands, though.
You can do this by three ways
1- The easiest option is to combine the two commands with the '&' symbol.
var processInfo = new ProcessStartInfo("cmd.exe", #"command1 & command2");
2- Set the working directory of the process through ProcessStartInfo.
var processInfo = new ProcessStartInfo("cmd.exe", #"your commands here ");
processInfo.UseShellExecute = false;
processInfo.WorkingDirectory = path;
3- Redirecting the input and output of the process. (Also done through the ProcessStartInfo).This is required when you like to send more input to the process, or when you want to get the output of the process
Also see this answer
I'm having some difficulty doing this without using a batch file. What I want to do is when a button is clicked, run the command line with a simple argument that I specify.
Here's my code so far:
ProcessStartInfo startInfo = new ProcessStartInfo("cmd.exe");
startInfo.WindowStyle = ProcessWindowStyle.Normal;
startInfo.UseShellExecute = true;
startInfo.Arguments = "dir";
Process.Start(startInfo);
string output = Process.StandardOutput.ReadToEnd();
txtblkOutput.Text = output;
However, this just opens a cmd window and nothing happens. The text box remains blank.
However I can do this:
var process = new Process();
process.StartInfo.FileName = "C:/Users/user/Documents/SUB-20 Tool/commands.bat";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
string output = process.StandardOutput.ReadToEnd();
txtblkOutput.Text = output;
Inside the batch file it just says dir. And this works, I get the output sent to my textbox.
Why does this work only with a batch file? Can I do this without it, with just using the argument property?
This is the excepted behaviour. When you execute cmd.exe with the argument dir, it does not execute the command.
As an exemple, see the screenshot below :
The correct way to execute a command in the arguments is the following :
cmd.exe /C <command>
I want to execute a command to lock the drive through bit locker when button is clicked. How to do this? I'm new in c#
The command is:
manage-bde -lock x:
How it will be send to console? here is the code
private void btnlock_Click(object sender, EventArgs e)
{
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 manage-bde -lock "+textBox1.Text+":";
process.StartInfo = startInfo;
process.Start();
}
You can use the Process class in System.Diagnostics namespace.
It should be something like this:
System.Diagnostics.Process.Start("manage-bde", "-lock x:");
The command isn't being executed because your command line doesn't know where to find the manage-bde program.
All you need to do is add the full path of the file like so:
startInfo.Arguments = #"/C C:\Program Files\Foo\manage-bde.exe -lock "+textBox1.Text+":";
Note: I'm not sure if the .exe part is necessary, but it doesn't hurt adding it in. Also, make sure you either use 2 backslashes (\\) or use the # before the quotation mark at the start.
How to hide the console from within this code? Currently the cmd console is shown everytime I run this code.
protected override void OnStart(string[] args)
{
String applicationName = "cmd.exe";
// launch the application
ApplicationLoader.PROCESS_INFORMATION procInfo;
ApplicationLoader.StartProcessAndBypassUAC(applicationName, out procInfo);
}
How can I execute a *.bat file from here? Can I simply can substitute the "cmd.exe" with "xxx.bat"?
Add a System Reference to the code;
using System Diagnostics;
Then use this code to Hide the CMD Window and run.
Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
cmd.StartInfo.Arguments = "Your arguments";
cmd.Start();
Try it with the Process Class instead of the ApplicationLoader (I´ve never heard of that class, is it a custom class?)
Code Example:
using System.Diagnostics;
Process pr = new Process();
pr.StartInfo.FileName = "cmd.exe";
pr.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
pr.Arguments = "xxx.bat";
pr.Start();