procStartInfo.RedirectStandardOutput not working properly?

AnkiIt_wizard5 66 Reputation points
2021-03-02T11:30:50.627+00:00

procStartInfo.RedirectStandardOutput not working properly i don't know why?
my code:
ProcessStartInfo procStartInfo = new ProcessStartInfo("cmd", "/q /c " + batchFile);
procStartInfo.RedirectStandardOutput = true;

                procStartInfo.RedirectStandardError = true;
                procStartInfo.UseShellExecute = false;
                procStartInfo.CreateNoWindow = true;

                Process proc = new Process();
                proc.StartInfo = procStartInfo;
                proc.StartInfo.CreateNoWindow = true;
                proc.Start();
                string result_prog = proc.StandardOutput.ReadToEnd(); // get result null
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,231 questions
.NET Runtime
.NET Runtime
.NET: Microsoft Technologies based on the .NET software framework.Runtime: An environment required to run apps that aren't compiled to machine language.
1,118 questions
{count} votes

Accepted answer
  1. Karen Payne MVP 35,036 Reputation points
    2021-03-02T13:32:05.783+00:00

    Here is an example that may help with whatever you are attempting. The code assumes PowerShell is in the path, gets the IP address without showing a window to a text file and reads back the results once the PowerShell code finishes executing using a language extension.

    This method will keep a windows form responsive and if this is not needed process.WaitForExit can be used.

    public static class Extensions
    {
        public static Task WaitForExitAsync(this Process process, CancellationToken cancellationToken = default)
        {
            if (process.HasExited)
            {
                return Task.CompletedTask;
            }
    
            var tcs = new TaskCompletionSource<object>();
    
            process.EnableRaisingEvents = true;
            process.Exited += (sender, args) => tcs.TrySetResult(null);
    
            if (cancellationToken != default)
            {
                cancellationToken.Register(() => tcs.SetCanceled());
            }
    
            return process.HasExited ? Task.CompletedTask : tcs.Task;
        }
    }
    

    Form code

    private async void button1_Click(object sender, EventArgs e)
    {
        PowerShellScriptExecute();
    }
    private string _fileName = "ipPower.txt";
    public async void PowerShellScriptExecute()
    {
        var start = new ProcessStartInfo
        {
            FileName = "powershell.exe",
            UseShellExecute = false,
            RedirectStandardOutput = true,
            Arguments = "Invoke-RestMethod ipinfo.io/ip", 
            CreateNoWindow = true
        };
    
        using var process = Process.Start(start);
        using var reader = process.StandardOutput;
    
        process.EnableRaisingEvents = true;
    
        var ipAddressResult = reader.ReadToEnd();
    
        await File.WriteAllTextAsync(_fileName, ipAddressResult);
        await process.WaitForExitAsync();
    
        Debug.WriteLine(await File.ReadAllTextAsync(_fileName));
    }
    
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Timon Yang-MSFT 9,571 Reputation points
    2021-03-03T08:49:41.26+00:00

    Please try if this code works for you:

                string file = @"D:\test\txt\test.bat";  
                var process = new Process();  
                var startinfo = new ProcessStartInfo(file);  
                startinfo.RedirectStandardOutput = true;  
                startinfo.UseShellExecute = false;  
                process.StartInfo = startinfo;  
      
                process.OutputDataReceived += (sender, argsx) => Console.WriteLine(argsx.Data);   
                process.Start();  
                process.BeginOutputReadLine();  
                process.WaitForExit();  
    

    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments