1

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?

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
  • please post the contents of your PreDefrag.bat file. And what Operating System are you using? Windows 7? Windows Vista? Windows Home Premium? Windows XP? Windows 2000? – Eric Leschinski Jan 19 '13 at 04:44

2 Answers2

2

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.

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
1

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);
        // ...
Tommaso Belluzzo
  • 23,232
  • 8
  • 74
  • 98
  • Why is it that when I use your code to run multiple commands, I cannot use "runas" I believe it would work great if I can, but when I add in the code for that, it doesn't pull up the UAC. – James Litewski Jan 24 '13 at 03:51