Skip to main content
 首页 » 编程设计

c#之在 C# 中从 DxDiag 获取输出

2024年02月06日15kuangbin

因此,我尝试在 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 位开关,突然间一切都像我预期的那样工作。

请您参考如下方法:

DxDiag 在 64 位操作系统上相当古怪。 32 位版本和 64 位版本接受不同的命令行开关,当您使用错误的开关时它不会发出任何提示。当您尝试在 32 位版本上使用/64 位选项时,/x 选项根本不起作用。并且 64 位版本不接受/64bit。当您在 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); 
        } 
    }