For example :
using (Process p = new Process())
{
p.StartInfo.FileName = "cleanmgr";
p.StartInfo.Arguments = "/d c";
p.Start();
}
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
I wrote a simple Windows form app to run Disk clean-up with the following code:
private void button1_Click(object sender, EventArgs e)
{
string strCmdText;
strCmdText = "/c cleanmgr /d c";
Process.Start("cmd.exe", strCmdText);
}
And it worked like a charm.
However, I thought why don't I just run my command without cmd, like when we type executables in the Run command such as mspaint, winword, msconfig, etc. So I made it like this instead:
private void button1_Click(object sender, EventArgs e)
{
Process.Start("/c cleanmgr /d c");
}
I also tried "cleanmgr /d c", but when I ran the app and clicked on that button, I received "Unhandled exception has occurred in your application...". But when I just used "cleanmgr", it worked.
What is the best and shortest way to run my command without cmd? And in terms of best practices or performance, do you think running it with cmd is better than running it without it?
For example :
using (Process p = new Process())
{
p.StartInfo.FileName = "cleanmgr";
p.StartInfo.Arguments = "/d c";
p.Start();
}
You can start a process and pass arguments using either of the following options:
In your command cleanmgr /d c
, the executable is cleanmgr
and arguments are /d c
. So you can run it like this:
var p = System.Diagnostics.Process.Start("cleanmgr", "/d c");
Or this:
var p = new System.Diagnostics.Process();
p.StartInfo.FileName = "cleanmgr";
p.StartInfo.Arguments = "/d c";
p.Start();
As mentioned in the documentations, the type is disposable and should be disposed as soon as you are done with it. You can dispose it by calling its Dsipose()
method in a try/finally block or use it in a using
block, for example:
var p = new System.Diagnostics.Process();
try
{
p.StartInfo.FileName = "cleanmgr";
p.StartInfo.Arguments = "/d c";
p.Start();
}
finally
{
p.Dispose();
}
Or
using (var p = new System.Diagnostics.Process())
{
p.StartInfo.FileName = "cleanmgr";
p.StartInfo.Arguments = "/d c";
p.Start();
}