如何在C#程序中获取vswhere命令的JSON格式输出?
解决C#调用vswhere无法获取JSON输出的问题
你碰到的这个问题根源很明确:你给vswhere传递参数的方式错了。vswhere是一个一次性的命令行工具,不是交互式的shell,不需要通过StandardInput给它发送命令——直接把参数放在进程启动的参数配置里就行。
问题出在哪?
你原来的代码启动vswhere.exe之后,通过StandardInput.WriteLine发送了vswhere -legacy -format json,但vswhere根本不会解析这个输入,它会把这段文本直接当成输出内容返回给你,这就是你拿到纯文本而非JSON的原因。
修正后的代码
直接把参数放到StartInfo.Arguments中,同时移除不必要的标准输入重定向配置:
using System.Diagnostics; using System.Reflection; using System.IO; var cmd = new Process(); // 定位vswhere.exe的路径 string vsWherePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "vswhere.exe"); cmd.StartInfo.FileName = vsWherePath; // 直接传递命令参数 cmd.StartInfo.Arguments = "-legacy -format json"; cmd.StartInfo.UseShellExecute = false; cmd.StartInfo.CreateNoWindow = true; cmd.StartInfo.RedirectStandardOutput = true; cmd.StartInfo.RedirectStandardError = true; cmd.Start(); // 先读取错误输出(避免缓冲区死锁) string errorOutput = cmd.StandardError.ReadToEnd(); string result = cmd.StandardOutput.ReadToEnd(); cmd.WaitForExit(); // 可选:检查错误输出以排查问题 if (!string.IsNullOrEmpty(errorOutput)) { Console.WriteLine($"vswhere错误信息: {errorOutput}"); } // 现在result就是标准的JSON格式,可以直接解析了 // Console.WriteLine(result);
额外提示
- 记得先读取
StandardError再读取StandardOutput,避免因为输出缓冲区满导致进程挂起的死锁问题 - 如果vswhere的路径不是和当前程序同目录,你也可以直接用
"vswhere.exe"(如果它在系统PATH里),不需要手动拼接路径
内容的提问来源于stack exchange,提问作者Nate276
相关产品推荐
相关产品推荐

