Zachieve Low-Impact Reuse: C# : Inside the Original Clipboard Writer: Listing 1

Roughly five years ago, I wrote a console application that piped output from any console application to the clipboard. This app has saved me a ton of time over the years, but it's time to update it.

using System;
using System.IO;

namespace Clipboard
{
  class ClipboardWriter
  {

    static private void copyStreamToClipboard (
        TextReader inStream)
    {
      System.Text.StringBuilder allStrs = new 
          System.Text.StringBuilder();
      string str;
      while (null != (str = inStream.ReadLine ()))
      {
        // Store it:
        allStrs.Append (str);
        allStrs.Append ("\r\n");
        // Pipe it to the output:
        System.Console.WriteLine (str);
      }
      System.Windows.Forms.Clipboard.SetDataObject 
          (allStrs.ToString (), true);
    }

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    
{
      if (args.Length == 1)
      {
        try 
        {
          TextReader inStream = new StreamReader (args[0]);
          copyStreamToClipboard (inStream);
        }
        catch (FileNotFoundException f)
        {
          System.Console.Error.WriteLine ("Input file: " +
				   args[0] + " not found.");
        }
        catch (DirectoryNotFoundException d)
        {
          System.Console.Error.WriteLine ("Input directory: " + 
              args[0] + " not found.");
        }
        catch (Exception i)
        {
          System.Console.Error.WriteLine ("Generic I/O Error");
        }
      } 
      else
      {
        copyStreamToClipboard (Console.In);
      }
    }
  }
}
comments powered by Disqus
Most   Popular
Upcoming Events

.NET Insight

Sign up for our newsletter.

Terms and Privacy Policy consent

I agree to this site's Privacy Policy.