Windows defrag is not recognized as an internal or external command, operable program or batch file

5k Views Asked by At

I'm working on making a tech-toolkit program, and included in this 'toolkit' will be a button which runs a defrag on the local disk. Currently the batch file I've made for this is simple, it just runs a basic fragmentation analysis:

defrag C: /A

The C# code behind the button that triggers this is:

System.Diagnostics.ProcessStartInfo procInfo = 
    new System.Diagnostics.ProcessStartInfo();
procInfo.Verb = "runas";
procInfo.FileName = "(My Disk):\\PreDefrag.bat";
System.Diagnostics.Process.Start(procInfo);

This code does exactly what I want, it calls UAC then launches my batch file with Administative Privledges. Though once the batch file is ran, the output I recieve to the command console is:

C:\Windows\system32>defrag C: /A
'defrag' is not recognized as an internal or external command, 
    operable program or batch file.

What causes this Error and how do I fix it?

2

There are 2 best solutions below

2
On

Check to make sure your defrag.exe file actually exists in C:\Windows\System32.

Try fully qualifying the 'defrag' command as:

C:\WINDOWS\system32\defrag.exe C: /A

Open up a cmd prompt and run this command: defrag.exe /? and post in the question what you get.

1
On

First of all: set yout project Platform Target property to Any CPU and untick the Prefer 32-bit option (99,9% this is the issue). Then... why starting a batch that invokes the command when you can just do this?

ProcessStartInfo info = new ProcessStartInfo();
info.Arguments = "/C defrag C: /A";
info.FileName = "cmd.exe";
info.UseShellExecute = false;
info.Verb = "runas";
info.WindowStyle = ProcessWindowStyle.Hidden;

Process.Start(info);

Works like a charm on my machine. For multiple commands:

ProcessStartInfo info = new ProcessStartInfo();
info.FileName = "cmd.exe";
info.RedirectStandardInput = true;
info.UseShellExecute = false;

Process cmd = Process.Start(info);

using (StreamWriter sw = p.StandardInput)
{
    if (sw.BaseStream.CanWrite)
    {
        sw.WriteLine(command1);
        sw.WriteLine(command2);
        // ...