OdeToCode IC Logo

Looking Back: My First C# Program

Monday, July 8, 2013

While digging through some directories of archived source code I found the first program I ever wrote in C#.

I’m not sure when I wrote this, but since there was a makefile in the directory I’m guessing this was still in the .NET 1.0 beta days of late 2000.

/******************************************************************************

CLIPBOARD.CS 

Based on the code and idea in Bill Wagner's VCDJ Fundamentals column.
This program takes piped input or a filename argument and copies all stream data 
to the clipboard. 

Examples:

dir | clipboard 

clipboard clipboard.cs

******************************************************************************/

using System;
using System.IO;
using System.WinForms;

class MainApp 
{  
    public static void Main( string[] args ) 
    {

        // The clipboard class uses COM interop. I figured this out because
        // calls to put data in the clipboard always failed and further 
        // investigation showed a failed hresult indicating no CoInitialize.
        // Here is the .NET equivalent:
        Application.OLERequired();
        
        TextReader textReader;
        if (args.Length == 0)
        {
            // take the piped input from stdin
            textReader = System.Console.In;
        }
        else
        {
            // open the text file specified on command line
            File file = new File(args[0]);
            textReader = file.OpenText();
        }
    
        string line;
        string allText = "";
        Boolean pipeFull = true;
        
        while(pipeFull)
        {
            try
            {
                // When the pipe is empty, ReadLine throws an exception
                // instead of the documented "return a null string" behavior.
                // When reading from a file a null string is returned.
                line = textReader.ReadLine();
                if( line == null )
                {
                    pipeFull = false;
                }
                else
                {
                    allText += line; 
                    allText += "\r\n";
                }
            }
            catch(System.IO.IOException ex)
            {
                if(ex.Message == "The pipe has been ended")
                {
                    pipeFull = false;
                }
                else
                {    
                    throw ex;
                }
            }
        } 

        Clipboard.SetDataObject(allText, true);
    }
}

The first thoughts that came to mind when seeing this code again were:

1) Wow, that’s a long function by today’s standards.

2) I could use this!

Before resharpering the program into shape, I did a quick search and discovered Windows now comes with such a program by default. It’s called clip. I guess I can leave the code in the archive.