cannot get input from redirect Standard Input

562 views Asked by At

I need get an enter command for my C# process.

my C# code work for test batch file, not for the fortran console application

I read this post: C# Process Call, Interact with Standard Input and Standard Output

but it does not work for me.

Anyone can give me some tips?

my sample batch file (test.bat):

note: this batch file simulate my another application.

@echo off
cls
dir
echo "please input enter key"
pause
tree

my C# code:

   private Process _process = null;
   private bool _bEnterCR = false;
   private void Begin_Click(object sender, RoutedEventArgs e)
    {
        this.tbOutput.Text = "";
        _bEnterCR = false;

        if (null != _process)
        {
            _process.Dispose();
        }

        string strPathName = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);            
        // Use ProcessStartInfo class
        _process = new Process();
        _process.StartInfo.CreateNoWindow = true;
        _process.StartInfo.UseShellExecute = false;
        _process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        _process.StartInfo.FileName = strPathName + "\\test.bat";
        _process.StartInfo.WorkingDirectory = strPathName + "\\Output\\";
        _process.StartInfo.RedirectStandardError = true;
        _process.StartInfo.RedirectStandardInput = true;
        _process.StartInfo.RedirectStandardOutput = true;
        //_process.EnableRaisingEvents = true;

        _process.OutputDataReceived += new DataReceivedEventHandler(OnOutputDataReceived);
        _process.ErrorDataReceived += new DataReceivedEventHandler(OnOutputDataReceived);            

        //_process.Exited += new EventHandler(OnProcessExited);

        _process.Start();

        _process.BeginOutputReadLine();
        _process.BeginErrorReadLine();
    }

    private void OnOutputDataReceived(object sender, DataReceivedEventArgs e)
    {
        if (String.IsNullOrEmpty(e.Data) == false)
        {
        if (e.Data.Contains("please input enter key") && _bEnterCR == false)
            {
                Debug.WriteLine("Pause Found, Entering <CR> command");
                // work for batch file, not for console application
                _process.StandardInput.Write(@"\r\n");
                _bEnterCR = true;
            }
            new Thread(() =>
            {
                this.Dispatcher.Invoke(new Action(() =>
                {
                    tbOutput.AppendText(e.Data + Environment.NewLine);
                }));
            }).Start();
        }
    }
0

There are 0 answers