How to launch SFC programatically on Windows Vista/7/8?

戏子无情 提交于 2019-12-01 21:13:10
David Heffernan

My experiments suggest that the issue is related to the WOW64 emulator. I have this code in a non-elevated WinForms app:

...
using System.Diagnostics;
...

ProcessStartInfo startInfo = new ProcessStartInfo("cmd", "/K sfc.exe /scannow");
  startInfo.UseShellExecute = true;
  startInfo.Verb = "runas";
Process.Start(startInfo);

From a 32 bit WOW64 process this fails with this message in the console window:

Windows Resource Protection could not start the repair service.

From a 64 bit process, the above code succeeds.

Indeed, I don't think .net or WinForms are relevant here at all. If I run 32 bit cmd.exe from the SysWOW64 folder, and then call sfc, I experience failure. But I am successful with the 64 bit cmd.exe.

And there's not even any need to bring cmd.exe into this at all. From a 64 bit process, running without elevation, the following succeeds:

...
using System.Diagnostics;
...

ProcessStartInfo startInfo = new ProcessStartInfo("sfc.exe", "/scannow");
startInfo.UseShellExecute = true;
startInfo.Verb = "runas";
Process.Start(startInfo);

So I guess the solution to your problem will involve either switching your main program to 64 bit (probably a little drastic), or splicing a 64 bit process into the chain so that the 64 bit sfc can be run.

AGnoob

With all the help here I ended up with this and it worked fine on 8.1 x64. Thank you all very much!

    ...
    using System.Diagnostics;
    ...

    private void button4_Click(object sender, EventArgs e)
    {
        string docs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        string snat = Environment.GetEnvironmentVariable("windir") + @"\sysnative\sfc.exe";

        Process a = new Process();
          a.StartInfo.FileName = snat;
          a.StartInfo.Arguments = "/SCANNOW";
          a.StartInfo.UseShellExecute = false;
          a.StartInfo.RedirectStandardOutput = true;
          a.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
          a.StartInfo.CreateNoWindow = true;
        a.Start();

        string output = a.StandardOutput.ReadToEnd();
        a.WaitForExit();

        using (StreamWriter outfile = new StreamWriter(docs + @"\Testoutput.txt"))
        {
            outfile.Write(output);
        }

        MessageBox.Show("DONE!");
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!