launching SFC from within a C# app

谁都会走 提交于 2019-12-02 12:07:48

问题


I have been searching and I cannot seem to get this work. I am trying to launch SFC from a button in a C# app. I am aware that it requires rights elevation and in the scope of what I am trying to do is behavior that I want.

I have tried: To run cmd as administrator along with command? Running CMD as administrator with an argument from C# and C# how to run a process(with arguments) through an administrator elevated cmd

The code I tried last was:

private void button6_Click(object sender, EventArgs e)
    {
        ProcessStartInfo procStartInfo = new ProcessStartInfo("cmd", "/c " + "processNeedToRun")
        {
            RedirectStandardError = true,
            RedirectStandardOutput = true,
            UseShellExecute = false,
            CreateNoWindow = true,
            Verb = "runas"
        };

    }

I either get no process launching at all the cmd window flashes saying incorrect credentials or the command was incorrect.

what am I doing wrong?

Per the comment added I changed it to this:

private void button6_Click(object sender, EventArgs e)
    {
        ProcessStartInfo procStartInfo = new ProcessStartInfo("cmd", "/c " + "sfc.exe /scannow")
        {
            RedirectStandardError = false,
            RedirectStandardOutput = false,
            UseShellExecute = true,
            CreateNoWindow = false,
            Verb = "runas"
        };

    }

and no change

EDIT:

So I managed to find a solution:

I created a new console app, edited the manifest to require admin and did this

Process.Start("CMD.exe", " /c SFC /Scannow");

That does have the behavior I want. Thanks for the help!


回答1:


Your console is not elevating, the problem is you can either use the Verb = "runas" and have it elevate or you can use UseShellExecute = false and redirect the outputs, you can not have both.

Your three options are:

  1. Use UseShellExecute = true and disable the redirections
  2. Add a manifest file to your program so it elevates itself as an administrator on start and it can then in turn launch administrative processes and monitor them.
  3. Do a combination of both by writing a 2nd exe that has a manifest file that always runs as administrator. Then have your 1st program launch the 2nd program with Verb = "runas", you then have your 2nd program start SFC with UseShellExecute = false. Your 2nd program then forwards the output via some form of IPC (WCF over named pipes would likely be easiest) to the first unelevated program to be displayed to the user.



回答2:


Try setting ProcesStartInfo.UserName and ProcessStartInfo.Password to impersonate the new process with elevated credentials.



来源:https://stackoverflow.com/questions/20086957/launching-sfc-from-within-a-c-sharp-app

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