问题
The below is just an example of the functionality.
I have a model like this:
public class StartParams
{
public string ParameterOne { get; set; }
public string ParameterTwo { get; set; }
public string ParameterThree { get; set; }
}
From a WPF app. I am serializing it as JSON like this:
var startParams = new StartParams
{
ParameterOne = "parameterOne",
ParameterTwo = "parameterTwo",
ParameterThree = "parameterThree"
};
var jsonStartParams = JsonConvert.SerializeObject(startParams);
Then I'm launching a .exe file with the JSON string as a parameter.
ProcessStartInfo info = new ProcessStartInfo
{
Arguments = jsonStartParams,
FileName = "C:\\Folder\\File.exe"
};
Process.Start(info);
In File.exe I have a Task which takes a string:
public static async Task DoSomething(string jsonStartParams)
{
var startParams = JsonConvert.DeserializeObject<StartParams>(jsonStartParams);
When debugging, I can call the static Main method in File.exe like this:
string[] parameters = {jsonStartParams};
File.Program.Main(parameters);
This works like a charm, but as soon as I call the .exe file with Process.Start, with the JSON string parameter, it fails with
Newtonsoft.Json.JsonReaderException
at the first prop in the JSON object.
Can someone please point me in the right direction of a solution?
Thank you!
回答1:
The quotes in jsonStartParams are making the argument separated into multiple arguments. Try escaping the quotes like this:
ProcessStartInfo info = new ProcessStartInfo
{
Arguments = "\"" + jsonStartParams.Replace("\"", "\\\"") + "\"",
FileName = "C:\\Folder\\File.exe"
};
回答2:
You probably need to escape the JSON string
something like this
JsonSerializerSettings settings = new JsonSerializerSettings
{
StringEscapeHandling = StringEscapeHandling.EscapeHtml
};
var jsonStartParams = JsonConvert.SerializeObject(startParams, settings);
来源:https://stackoverflow.com/questions/46848338/how-do-i-start-a-exe-with-a-json-string-as-parameter-correctly