C#C
C#3y ago
Seventy

❔ Getting $StandardIn has not been redirected.$ Error...

    public class CmdExecutor
    {
        private Process process;

        public CmdExecutor()
        {
            InitializeProcess();
        }

        private void InitializeProcess()
        {
            process = new Process();

            ProcessStartInfo startInfo = new ProcessStartInfo
            {
                FileName = "cmd.exe",
                RedirectStandardOutput = true,
                RedirectStandardInput = true,
                UseShellExecute = false,
                CreateNoWindow = true
            };
       
            process.StartInfo = startInfo;
            
          
            process.OutputDataReceived += Process_OutputDataReceived;

            process.Start();
            process.BeginOutputReadLine();
        }

        public string ExecuteCommand(string command)
        {
            try
            {
                process.StandardInput.WriteLine(command);
                process.StandardInput.Flush();
                return "";
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error executing command: " + ex.Message);
                return "";
            }
        }

        private void Process_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            Console.WriteLine(e.Data);
        }

        public void CloseProcess()
        {
            if(process != null)
            {

            process.Close();
            process.Dispose();
            }
        }
    }


When i run the execute command method i get StandardIn has not been redirected. as an error.
Does anyone know what's up with that?
Was this page helpful?