0

So for context, I'm trying to create a program in C#, which starts a CMD prompt and executes the command "netsh wlan show profiles". For this I start a CMD process and redirect the console input (and later output), before using StreamWriter to execute the command.

This works with commands like echo, ipconfig, @echo off, color... and so on. But if I try netsh the process restarts over and over again:

Microsoft Windows [Version 10.0.22000.613]
(c) Microsoft Corporation. Alle Rechte vorbehalten.

C:\Users\Heinz Mütze\source\repos\netsh\netsh\bin\Debug>netsh wlan show profiles
Microsoft Windows [Version 10.0.22000.613]
(c) Microsoft Corporation. Alle Rechte vorbehalten.

C:\Users\Heinz Mütze\source\repos\netsh\netsh\bin\Debug>netsh wlan show profiles
Microsoft Windows [Version 10.0.22000.613]
(c) Microsoft Corporation. Alle Rechte vorbehalten.

C:\Users\Heinz Mütze\source\repos\netsh\netsh\bin\Debug>netsh wlan show profiles
Microsoft Windows [Version 10.0.22000.613]
(c) Microsoft Corporation. Alle Rechte vorbehalten.

and so on...

Anyone knows how I can fix it? Heres my code:

using System.IO;
using System.Diagnostics;
using System;
using System.Linq;
using System.Threading;

namespace netsh
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var p = new Process();
            var startinfo = new ProcessStartInfo("cmd.exe")
            {
                RedirectStandardInput = true,
                RedirectStandardOutput = false,
                UseShellExecute = false
            };
            p.StartInfo = startinfo;
            p.Start();

            using (StreamWriter sw = p.StandardInput)
            {
                if (sw.BaseStream.CanWrite)
                {
                    sw.WriteLine("netsh wlan show profiles");
                    Thread.Sleep(5000);
                    p.Kill();
                }
            }
//            using (StreamReader sr = p.StandardOutput)
//            {
//                if (sr.BaseStream.CanRead)
//                {
//                    string output;
//                    output = sr.ReadToEnd();
//                    File.WriteAllText(@"C:\Users\Heinz Mütze\Desktop\CMD-Test\netsh.txt", output);
//                }
//            }
        }
    }
}
hkutluay
  • 6,794
  • 2
  • 33
  • 53
  • Probably better to use Interop/Pinvoke for this. Relevant: https://stackoverflow.com/a/31172051/14868997 – Charlieface May 03 '22 at 09:17
  • Does this answer your question? [C# - Realtime console output redirection](https://stackoverflow.com/questions/4501511/c-sharp-realtime-console-output-redirection) – McNets May 03 '22 at 09:17
  • The code works without any problem for me. – shingo May 03 '22 at 10:57

1 Answers1

0

I kinda found the problem. I think something messed up the file. I created a new one and copy pasted the code and everything works just fine.