如何解决带空格的文件路径作为.exe程序参数时的拆分问题
解决带空格的文件路径作为参数传递的问题
直接修改Arguments的赋值逻辑,把文件路径用单引号(或双引号)包裹起来,确保整个路径被识别为单个参数:
private static void CreateBinFromHex(String pathToHexFile) { // Use ProcessStartInfo class ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.CreateNoWindow = false; startInfo.UseShellExecute = false; // 用Path.Combine更安全地拼接路径,避免斜杠问题 startInfo.FileName = Path.Combine(System.IO.Directory.GetCurrentDirectory(), "hex2bin.exe"); startInfo.WindowStyle = ProcessWindowStyle.Hidden; // 用单引号包裹路径,对应你终端测试有效的方式 startInfo.Arguments = $"'{pathToHexFile}'"; // 如果双引号更兼容,也可以这样写(需要转义双引号) // startInfo.Arguments = $"\"{pathToHexFile}\""; try { // Start the process with the info we specified. // Call WaitForExit and then the using statement will close. using (Process exeProcess = Process.Start(startInfo)) { exeProcess.WaitForExit(); } } catch(SystemException e) { MessageBox.Show(e.Message); } }
原理说明
当参数包含空格时,系统默认会将空格视为参数分隔符,把路径拆分成多个独立参数。用引号(单引号或双引号)包裹整个路径后,系统会将引号内的内容识别为单个完整参数,不会拆分。
另外,用Path.Combine替换直接字符串拼接路径是更稳妥的做法,它会自动处理不同系统的路径分隔符,避免因手动拼接导致的路径错误。
内容的提问来源于stack exchange,提问作者Tinaye Tsinakwadi
相关产品推荐
相关产品推荐

