[英]How to launch SFC programatically on Windows Vista/7/8?
我一直在努力解決Chris Iverson在其他Stackoverflow問題中遇到的問題 。
我想以編程方式啟動SFC
( 系統文件檢查器工具)。
它適用於Windows XP:
private void RunSfc()
{
ProcessStartInfo startInfo = new ProcessStartInfo("cmd", "/K sfc.exe /scannow");
System.Diagnostics.Process.Start(startInfo);
}
這在Windows XP下做工作以外的變種:
//Launch SFC directly
ProcessStartInfo startInfo = new ProcessStartInfo("sfc.exe", "/scannow");
System.Diagnostics.Process.Start(startInfo);
//Use full path to SFC
String sfcPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "sfc.exe");
ProcessStartInfo startInfo = new ProcessStartInfo(sfcPath, "/scannow");
Windows 7上的相同代碼失敗(啟動程序以管理員身份運行)。 出現控制台窗口,但SFC給出錯誤:
Windows Resource Protection could not start the repair service.
但是,如果我從單獨的提升命令提示符手動運行sfc /scannow
,它可以工作:
所以Windows Vista / 7/8顯然會發生一些奇怪的事情。 我完全不知道是什么。 但它可能與UAC,UIPI,會話0 isoloation或控制台窗口由CSRSS運行的事實有關
但是,我仍然不明白這個問題。
解決克里斯的問題本來不錯,因為我想做他所做的事情。
請記住 :我的代碼已經以管理員身份運行。 我右鍵單擊並以管理員身份啟動 :
這並不意味着問題不是與UAC相關的其他微妙問題,而是因為我作為標准用戶運行的事實。
private void button1_Click(object sender, EventArgs e)
{
RunSfc();
}
原來有一個32位版本的cmd.exe
和一個32位版本的sfc.exe
:
如果運行提升的32位cmd ,則32位或64位版本的sfc都不起作用。
因此,難題就變成了如何從32位進程啟動64位 cmd.exe
。 這可能意味着難題變成如何從32位進程中找到 64位版本的cmd.exe
,給出:
System32
文件夾的名稱 我的實驗表明該問題與WOW64模擬器有關。 我在非提升的WinForms應用程序中有這個代碼:
...
using System.Diagnostics;
...
ProcessStartInfo startInfo = new ProcessStartInfo("cmd", "/K sfc.exe /scannow");
startInfo.UseShellExecute = true;
startInfo.Verb = "runas";
Process.Start(startInfo);
在32位WOW64進程中,此消息在控制台窗口中失敗:
Windows資源保護無法啟動修復服務。
從64位進程,上面的代碼成功。
實際上,我認為.net或WinForms在這里根本不相關。 如果我從SysWOW64文件夾運行32位cmd.exe,然后調用sfc,我會遇到故障。 但我使用64位cmd.exe成功。
而且甚至根本不需要將cmd.exe帶入此中。 從64位進程運行,不進行提升,以下成功:
...
using System.Diagnostics;
...
ProcessStartInfo startInfo = new ProcessStartInfo("sfc.exe", "/scannow");
startInfo.UseShellExecute = true;
startInfo.Verb = "runas";
Process.Start(startInfo);
所以我猜你的問題的解決方案將涉及將主程序切換到64位(可能有點劇烈),或者將64位進程拼接到鏈中,以便可以運行64位sfc
。
在這里得到了所有的幫助,我最終得到了這個,它在8.1 x64上運行良好。 非常感謝你們!
...
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!");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.