How to fix winmgmt error code 0x8007007E?

0

I'm making C# wrapper class for executing winmgmt and command keeps failing.

I tried setting the StartInfo.Verb parameter to "runas" but it did not help. C# application is already elevated.

Running command winmgmt /verifyrepository in elevated command prompt works just fine.

public static void VerifyRepository()
{
var p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = @"winmgmt";
p.StartInfo.Arguments = @"/verifyrepository";
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
WMIVerifyResultReceived?.Invoke(null, new WMIVerifyResultReceivedEventArgs(output));
}

When ran in cmd output is

WMI repository is consistent

but when ran using VerifyRepository() method i keep getting this output on same machine:

WMI repository verification failed Error code: 0x8007007E

c#
asked on Stack Overflow Aug 6, 2019 by Nicky

1 Answer

0

The problem was caused because app was run in WOW64 (32bit on 64bit) so the path of winmgmt was in systemwow64 folder and service was running in 64bit mode. Fixed it by unchecking prefer 32bit in build options. Another way to fix this without disabling prefer 32bit is to use wow64apiset call Wow64DisableWow64FsRedirection at the start of verifyrepository method and then at the end to call Wow64RevertWow64FsRedirection function like shown here:

[DllImport("kernel32.dll", SetLastError = true)]
static extern bool Wow64DisableWow64FsRedirection(ref IntPtr ptr);

[DllImport("kernel32.dll", SetLastError = true)]
static extern bool Wow64RevertWow64FsRedirection(IntPtr ptr);

public static void VerifyRepository()
{
var wow64Value = IntPtr.Zero;
Wow64DisableWow64FsRedirection(ref wow64Value);
var p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = @"winmgmt";
p.StartInfo.Arguments = @"/verifyrepository";
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
Wow64RevertWow64FsRedirection(wow64Value);
WMIVerifyResultReceived?.Invoke(null, new WMIVerifyResultReceivedEventArgs(output));
}

Note that if you have prefer 32bit unchecked there is no need to use wow64apiset calls.

answered on Stack Overflow Aug 10, 2019 by Nicky

User contributions licensed under CC BY-SA 3.0