Reading/Writing to a command line program in c#

后端 未结 3 726
夕颜
夕颜 2021-01-16 00:09

I\'m trying to talk to a command-line program from C#. It is a sentiment analyser. It works like this:

CMD> java -jar analyser.jar

>

3条回答
  •  北恋
    北恋 (楼主)
    2021-01-16 00:20

    This is not a general question, but rather a application-specific one. I just happened to be working on the same thing. We probably should not discuss about this here, but forgive me I just want to help.

    The key point is that you need to enter the right arguments for the jar

    var processInfo = new ProcessStartInfo("java.exe", "-jar SentiStrengthCom.jar stdin sentidata data201109/ scale"){ ... }
    

    Below is a working solution:

        // Start the java server, probably in a background thread
        void bgw_DoWork(object sender, DoWorkEventArgs e)
        {
            string directory = ...; // the directory of jar
    
            var processInfo = new ProcessStartInfo("java.exe", "-jar SentiStrengthCom.jar stdin sentidata data201109/ scale")
            {
                // Initialize properties of "processInfo"
                CreateNoWindow = true,
                UseShellExecute = false, 
                WorkingDirectory = directory,
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                RedirectStandardInput = true,
            };
    
            JavaSentiStrength = new Process();
            JavaSentiStrength.StartInfo = processInfo;
    
            JavaSentiStrength.Start();
    
            Console.WriteLine("SentiStrengthCom Java is running...");
    
            JavaSentiStrength.WaitForExit();
    
            int exitCode = 0;
            if (JavaSentiStrength != null) exitCode = JavaSentiStrength.ExitCode;
            Debug.WriteLine("Java SentiStrengthCom closed down! " + exitCode);
            JavaSentiStrength.Close();
            JavaSentiStrength = null;
    
        }
    
        // A button click
        private void btnRequest_Click(object sender, EventArgs e)
        {
            JavaSentiStrength.StandardInput.WriteLine("love you ");
            string s_out = JavaSentiStrength.StandardOutput.ReadLine();
            Debug.WriteLine("SentiStrengthCom output: " + s_out);
        }
    

    The output is

    SentiStrengthCom output: 3 -1 2

    Hope it helps!

提交回复
热议问题