嗨,我有一个应用程序,我需要从另一个exe执行。当我作为命令行参数传递时,相同的 json 字符串工作正常;但是当我将其作为进程启动信息参数传递时失败。
命令行参数:
输入(即参数[0](:"{"mydllpath":"D:\dll","FilePath":"D:\Input\abc.doc", "Attribute":"word"}"
Console.Writeline:{"mydllpath":"D:\dll","FilePath":"D:\Input\abc.doc", "Attribute":"word"}
成功解析
进程启动信息参数:
输入:"{"mydllpath":"D:\dll","FilePath":"D:\Input\abc.doc", "Attribute":"word"}"
Console.Writeline:{"mydllpath":"D:dll","FilePath":"D:Inputabc.doc", "Attribute":"word"}
解析失败:解析值时遇到意外字符:D。
ProcessStartInfo psi = new ProcessStartInfo("D:\ETS\AE\bin\Debug\AE.exe");
string json = "{"mydllpath":"D:\dll","FilePath":"D:\Input\abc.doc", "Attribute":"word"}";
psi.Arguments = json;
Process p = new Process();
Debug.WriteLine(psi.FileName + " " + psi.Arguments);
p.Start();
p.StartInfo = psi;
传递的参数未正确转义
它应该被正确转义
var jsonString = "{"mydllpath":"D:dll","FilePath":"D:Inputabc.doc", "Attribute":"word"}";
var args = string.Format(""""{0}"""", jsonString);
psi.Arguments = args;
//...
引用进程启动信息参数属性
这么多年没有答案... 我遇到了问题,最后得到了一种棘手的方式工作,在我的情况下这是一个节点进程。希望它能有所帮助。
-
将 .net 端参数中的 " 替换为单引号 '(因为进程参数将 " 作为无引号,因此您的进程将收到一个不带引号的 json 字符串!!(
argumentStr= argumentStr.Replace("", "'"(; 过程。StartInfo.Arguments = $"app.js "{argumentStr}">
-
在节点端将 ' 替换为 ">
let arg= process.argv[2]; arg = arg.replace(/'/g, '"'(; const yourObject = JSON.parse(arg(;
您需要用 " 包装参数,并通过将其替换为 '"' 来转义 '"' 符号。
下面是使用 JSON 命令行参数启动应用程序的示例代码
var argumentString = JsonSerializer.Serialize(new
{
DeviceId = _deviceInfo?.DeviceId,
ApplicationStartUrl = _deviceInfo?.AppStartUrl
}).Replace(""", """");
argumentString = $""{argumentString}"";
var processStartupInfo = new ProcessStartInfo(Path.Combine("Application",
_configuration.Executable ?? ""), argumentString);
processStartupInfo.WorkingDirectory = Path.Combine(Assembly.GetExecutingAssembly().Location, "Application");
_applicationProcess = Process.Start(processStartupInfo);
唯一对我有用的就是转换为base64,然后转换回来
string args = Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(request)));
using (Process process = new Process())
{
process.StartInfo = new ProcessStartInfo()
{
FileName = Assembly.GetExecutingAssembly().Location,
Arguments = args,
UseShellExecute = false,
CreateNoWindow = true
};
process.Start();
process.WaitForExit(timeoutSeconds * 1000);
}
byte[] bytes = Convert.FromBase64String(args);
string requestStr = System.Text.Encoding.UTF8.GetString(bytes);
ReportRequest request = JsonConvert.DeserializeObject<ReportRequest>(requestStr);