c# - 如何在 C# 中捕获 Shell 命令输出?

标签 c# .net registry capture

总结:

  • 查询远程机器上的注册表
  • 捕获输出以在应用程序中使用
  • 需要在 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/

相关文章:

c# - ServiceStack OrmLite 同类型负载的多个引用

windows - 使用 (SetACL) 自动执行 Windows HKCU 注册表权限的批处理文件

c# - 如何在图像上放置标签

c# - 在这种情况下使用按位与 (&)

c# - 覆盖被覆盖的方法 (C#)

.net - NCache 通用类型处理程序实现

c# - 在构建 .NET 4.0 项目时自动构建 .NET 4.5 项目?它不需要被引用

c# - 如果不存在,将 key 添加到注册表

windows - 如何仅在驱动器 C :\? 上向 Shell 菜单添加条目

c# - Entity Framework 模型-第一个可为空外键