Welcome to MSDN Blogs Sign in | Join | Help

Argument processing and C# 2.0 iterators

Sometime, you want to process this command-line argument:

C:\>aprogram arg0 arg1 @arg2 arg3 @arg4
arg0, arg1, arg3 are actual data to process whereas arg2 and arg4 are text file names where each text line inside is another actual data to process (aka response files).

Here is a way to convey such a processing using C# 2.0 iterators:
using System;
using System.IO;
using System.Collections;

class exe
{
  static void Main(string[] args)
  {
    foreach(string arg in GetArgs(args))
      process(arg);
  }

  static void process(string arg)
  {
    Console.WriteLine(arg);
  }

  static IEnumerable GetArgs(params string[] args)
  {
    foreach(string s in args)
    {
      if(s.StartsWith("@"))
        foreach(string sql in GetArgsInFile(s.Substring(1)))
          yield return sql;
      else
        yield return s;
    }
  }

  static IEnumerable GetArgsInFile(string filename)
  {
    using (StreamReader reader = File.OpenText(filename))
    {
      string line = reader.ReadLine();
      while (line != null)
      {
        foreach(string innerline in GetArgs(line))
          yield return innerline;
        line = reader.ReadLine();
      }
    }
  }
}

Published Saturday, March 04, 2006 12:52 AM by marcod
Filed under:

Comments

# Interesting Finds

Saturday, March 04, 2006 5:55 AM by Jason Haley

# A basic and focused utility to send SQL statements with ADO.NET



Sometimes, I just need to quickly send SQL queries or commands to a SQL database one by one or in...
Thursday, March 09, 2006 2:16 PM by Marco Dorantes' WebLog
Anonymous comments are disabled
 
Page view tracker