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
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)
}
}
This will give the stdout to the clipboard.
dir | clip
Where dir is just my test command...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With