Search code examples
c#console-applicationprogram-entry-point

How can I return a List<string> from a console application?


I am calling a console application from a Windows forms application. I want to get a list of strings back from the console application. This is my simplified code...

[STAThread]
static List<string> Main(string[] args)
{      
    List<string> returnValues = new List<string>();
    returnValues.Add("str_1");
    returnValues.Add("str_2");
    returnValues.Add("str_3");

    return returnValues;
}

Solution

  • In this way you cannot. Main can return only void or int. But you can send list to standard output and read it in another app.

    In console app add this:

    Console.WriteLine(JsonConvert.SerializeObject(returnValues));
    

    And in caller app:

    Process yourApp= new Process();
    yourApp.StartInfo.FileName = "exe file";
    yourApp.StartInfo.Arguments = "params";
    yourApp.StartInfo.UseShellExecute = false;
    yourApp.StartInfo.RedirectStandardOutput = true;
    yourApp.Start();    
    
    string output = yourApp.StandardOutput.ReadToEnd();
    List<string> list = JsonConvert.DeserializeObject<List<string>>(output);
    
    yourApp.WaitForExit();