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();
}
}
}
}
Comments
- Anonymous
March 09, 2006
Sometimes, I just need to quickly send SQL queries or commands to a SQL database one by one or in...