从C#获取DxDiag的输出

时间:2015-01-28 10:18:34

标签: c#

所以我试图在C#中自动化DxDiag的输出,我遇到了一个问题。程序运行但不生成任何输出文件。可能是我没有正确传递参数或者我误解了某些东西。

在正常命令行中运行DxDiag时,我执行此操作并按预期工作:

dxdiag -64bit -x C:\dxFromCode.xml

这就是我尝试在代码中执行此操作的方式:

//Create process
System.Diagnostics.Process pProcess = new System.Diagnostics.Process();

pProcess.StartInfo.FileName = "dxdiag";

pProcess.StartInfo.Arguments = @"64bit x C:\dxFromCode.xml";

pProcess.StartInfo.UseShellExecute = false;

//Set output of program to be written to process output stream
pProcess.StartInfo.RedirectStandardOutput = false;

//Start the process
pProcess.Start();

//Wait for process to finish
pProcess.WaitForExit();

编辑:

好的,所以我将代码更改为x64版本。这使得dxdiag自动启动为64位版本。然后我可以拿走64位开关,突然一切都按照我的预期运行。

3 个答案:

答案 0 :(得分:4)

DxDiag在64位操作系统上非常暴躁。 32位版本和64位版本接受不同的命令行开关,当您使用错误的命令行开关时它不会窥视。当您尝试在32位版本上使用/ 64bit选项时,/ x选项不起作用。并且64位版本不接受/ 64位。当您在64位操作系统上运行并且程序以32位模式运行时,您必须显式启动64位版本。

这在我的Win81 x64机器上运行良好:

    private string RunDxDiag() {
        var psi = new ProcessStartInfo();
        if (IntPtr.Size == 4 && Environment.Is64BitOperatingSystem) {
            // Need to run the 64-bit version
            psi.FileName = System.IO.Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.Windows),
                "sysnative\\dxdiag.exe");
        }
        else {
            // Okay with the native version
            psi.FileName = System.IO.Path.Combine(
                Environment.SystemDirectory, 
                "dxdiag.exe");
        }
        string path = System.IO.Path.GetTempFileName();
        try {
            psi.Arguments = "/x " + path;
            using (var prc = Process.Start(psi)) {
                prc.WaitForExit();
                if (prc.ExitCode != 0) {
                    throw new Exception("DXDIAG failed with exit code " + prc.ExitCode.ToString());
                }
            }
            return System.IO.File.ReadAllText(path);
        }
        finally {
            System.IO.File.Delete(path);
        }
    }

答案 1 :(得分:0)

尝试将/ user:Administrator cmd / K添加到arguments语句中。像这样:

Arguments = "/user:Administrator \"cmd /K " + command + "\""

命令为64bit x C:\dxFromCode.xml。我认为您的问题可能是您需要以管理员身份运行cmd。

答案 2 :(得分:0)

奇怪的是,汉斯的代码并不适合我。我发现WaitForExit()调用将在文件被读取之前返回。作为一种解决方法,我补充说:

int nTries = 0;
do
{
  string szText = System.IO.File.ReadAllText(path);
  if (szText.Length != 0)
  {
    return szText;
  }
  else
  {
    System.Threading.Thread.Sleep(1000);
  }
} while (nTries++ < 10);
return "";