总结:
- 查询远程机器上的注册表
- 捕获输出以在应用程序中使用
- 需要在 csharp 中
- 目前使用的所有方法只能在 native 查询
- 不胜感激
全期:
我需要找到一种在 csharp 中运行命令行命令并捕获其输出的方法。我知道如何在 Perl 中执行此操作,下面是我将在 Perl 中使用的代码。
#machine to check
my $pc = $_[0];
#create location of registry query
my $machine = "\\\\".$pc."\\HKEY_USERS";
#run registry query
my @regQuery= `REG QUERY $machine`;
欢迎就如何在 csharp 中执行此操作提出任何建议。到目前为止,我已经尝试使用 RegistryKey OurKey = Registry.Users 方法,效果很好,但我无法在远程计算机上查询注册表。
如果您需要更多信息,请告诉我。
解决方案:(感谢@Robaticus)
private void reg(string host)
{
string build = "QUERY \\\\" + host + "\\HKEY_USERS";
string parms = @build;
string output = "";
string error = string.Empty;
ProcessStartInfo psi = new ProcessStartInfo("reg.exe", parms);
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
psi.UseShellExecute = false;
System.Diagnostics.Process reg;
reg = System.Diagnostics.Process.Start(psi);
using (System.IO.StreamReader myOutput = reg.StandardOutput)
{
output = myOutput.ReadToEnd();
}
using (System.IO.StreamReader myError = reg.StandardError)
{
error = myError.ReadToEnd();
}
Output.AppendText(output + "\n");
}
最佳答案
您可能需要稍微调整一下,但这里有一些(对原始代码稍作修改)重定向进程的 stdout 和 stderr 的代码:
string parms = @"QUERY \\machine\HKEY_USERS";
string output = "";
string error = string.Empty;
ProcessStartInfo psi = new ProcessStartInfo("reg.exe", parms);
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
psi.UseShellExecute = false;
System.Diagnostics.Process reg;
reg = System.Diagnostics.Process.Start(psi);
using (System.IO.StreamReader myOutput = reg.StandardOutput)
{
output = myOutput.ReadToEnd();
}
using(System.IO.StreamReader myError = reg.StandardError)
{
error = myError.ReadToEnd();
}
关于c# - 如何在 C# 中捕获 Shell 命令输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4587415/