8

I want to copy the whole output of a console application programmatically into clipboard (so user can get this automatically without tinkering with cmd window).

I know how to access clipboard. I dont know how to get a console window text from C#.

C# 3.5 / 4

Boppity Bop
  • 9,613
  • 13
  • 72
  • 151

2 Answers2

6

One basic solution below (just redirecting standard output to a StringBuilder instance). You probably need to add the reference to System.Windows.Forms yourself in a console application.

using System;
using System.IO;
using System.Text;
using System.Windows.Forms;

public class Redirect
{
    [STAThread()]
    public static void Main()
    {
        StringBuilder sb = new StringBuilder();
        StringWriter sw = new StringWriter(sb);

        Console.SetOut(sw); // redirect

        Console.WriteLine("We are redirecting standard output now...");

        for (int i = 0; i < 10; i++) { Console.WriteLine(i); }

        sw.Close();
        StringReader sr = new StringReader(sb.ToString());
        string completeString = sr.ReadToEnd();
        sr.Close();

        Clipboard.SetText(sb.ToString());
        Console.ReadKey(); // just wait... (press ctrl+v afterwards)
    }
}
ChristopheD
  • 112,638
  • 29
  • 165
  • 179
2

This will give the stdout to the clipboard.

dir | clip

Where dir is just my test command...

Örjan Jämte
  • 14,147
  • 1
  • 23
  • 23