2016-08-14 1 views
0

J'essaie d'écrire la sortie de la fenêtre de commande dans un fichier, je peux obtenir la sortie correctement, et l'afficher en utilisant la console. Cependant, il ne semble pas être connecté au fichier que je veux écrire?Écrire la sortie de la console dans un fichier en C#?

using (StreamWriter sw = new StreamWriter(CopyingLocation, true)) 
    { 
    Process cmd = new Process(); 

    cmd.StartInfo.FileName = "cmd.exe"; 
    cmd.StartInfo.RedirectStandardInput = true; 
    cmd.StartInfo.RedirectStandardOutput = true; 
    cmd.StartInfo.CreateNoWindow = false; 
    cmd.StartInfo.UseShellExecute = false; 

    cmd.Start(); 


    string strCmdText = "Some Command"; 
    string cmdtwo = "Some Other Command"; 


    cmd.StandardInput.WriteLine(cmdtwo); 
    cmd.StandardInput.WriteLine(strCmdText); 
    cmd.StandardInput.Flush(); 
    cmd.StandardInput.Close(); 

    //Writes Output of the command window to the console properly 
    Console.WriteLine(cmd.StandardOutput.ReadToEnd()); 

    //Doesn't write the output of the command window to a file 
    sw.WriteLine(cmd.StandardOutput.ReadToEnd()); 
    } 

Répondre

4

Lorsque vous appelez ReadToEnd() il va lire tout et toute la production a été consommée. Vous ne pouvez pas l'appeler à nouveau.

Vous devez stocker la sortie dans une variable et la sortir dans la console et écrire dans un fichier.

string result = cmd.StandardOutput.ReadToEnd(); 
Console.WriteLine(result); 
sw.WriteLine(result); 
+0

Merci, ça a marché! Impressionnant! – chillax786