C#调用cmd执行含俄文路径的adb命令失败 手动运行正常如何解决
问题根因
本质是cmd.exe的默认编码与.NET的StandardInput默认编码不匹配,导致西里尔字符被错误转码,adb无法识别目标路径。
解决方案
方案1:直接调用adb(最优,推荐)
不要通过cmd.exe中转,直接将adb作为启动进程,避免cmd的编码解析链路:
using System.Diagnostics; using System.Text; Process p = new Process(); // 若已将adb加入系统PATH,可直接写"adb.exe",否则填adb的完整路径 p.StartInfo.FileName = "adb.exe"; // 参数直接放到Arguments属性,无需额外转义cmd特殊字符 p.StartInfo.Arguments = @"-s 127.0.0.1:62001 install ""D:\Рабочий_стол\Facebook.apk"""; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.CreateNoWindow = true; p.StartInfo.UseShellExecute = false; // 显式匹配adb输出编码 p.StartInfo.StandardOutputEncoding = Encoding.UTF8; p.Start(); p.WaitForExit(); return p.StandardOutput.ReadToEnd();
该方案直接绕开cmd编码问题,90%以上类似场景可直接解决。
方案2:保留cmd调用的修复方法
如果必须使用cmd执行命令,需要先切换cmd代码页为UTF-8,同时显式设置输入输出编码:
using System.Diagnostics; using System.Text; string command = @"adb -s 127.0.0.1:62001 install ""D:\Рабочий_стол\Facebook.apk"""; Process p = new Process(); p.StartInfo.FileName = "cmd.exe"; p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.CreateNoWindow = true; p.StartInfo.UseShellExecute = false; // 显式设置输入输出编码为UTF8 p.StartInfo.StandardInputEncoding = Encoding.UTF8; p.StartInfo.StandardOutputEncoding = Encoding.UTF8; p.Start(); // 先切换cmd代码页为UTF-8,>nul屏蔽切换命令的输出 p.StandardInput.WriteLine("chcp 65001 >nul"); p.StandardInput.WriteLine(command); p.StandardInput.Flush(); p.StandardInput.Close(); p.WaitForExit(); return p.StandardOutput.ReadToEnd();
方案3:路径转8.3短文件名(终极兼容方案)
如果上述方案都无效,可以调用Windows API将带特殊字符的长路径转换为不含非ASCII字符的8.3格式短路径,完全规避编码问题:
首先引入Win32 API声明:
using System.Runtime.InteropServices; using System.Text; [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] private static extern uint GetShortPathName(string lpszLongPath, StringBuilder lpszShortPath, uint cchBuffer); // 封装路径转换方法 public static string GetShortPath(string longPath) { StringBuilder shortPath = new StringBuilder(256); GetShortPathName(longPath, shortPath, (uint)shortPath.Capacity); return shortPath.ToString(); }
调用时替换为转换后的短路径即可:
string apkPath = GetShortPath(@"D:\Рабочий_стол\Facebook.apk"); string command = $@"adb -s 127.0.0.1:62001 install ""{apkPath}""";
所有Windows系统原生支持8.3短路径,无需额外依赖,兼容性最高。
内容的提问来源于stack exchange,提问作者prishelets
相关产品推荐
相关产品推荐

