Maybe I'm oversimplifying the issue here, but try the following.
In your last loop, try the following
foreach (DataRow dr in dt.Rows)
{
StringBuilder sb = new StringBuilder();
string agencyNumber;
int index = dr[12].ToString().IndexOf("|");
if (index > 0)
{
agencyNumber = dr[12].ToString().Substring(0, index);
}
if (dr[0].ToString() != "2")
{
if (dr[9].ToString() != "Total Amount")
{
sb.Append("6 ");
sb.Append(dr[9].ToString().Replace(".", "").Replace(",", "").PadLeft(10, '0'));
sb.Append((dr[12].ToString().Remove(0, index)).PadRight(15, ' '));
sb.Append((dr[13].ToString() + " " + dr[14].ToString()).PadRight(40));
sb.Append(sw2.NewLine);
}
}
}
sb.Append("9");
sb.Append(sw2.NewLine);
string file = "C:\\inetpub\\temp\\" + agencyNumber + "-Authorize.Net - " + date1 + " @ " + date2 + ".ach";
using (StreamWriter sw2 = new StreamWriter(file, true)
{
sw2.WriteLine(sb.ToString());
}
So I'm using the foreach loop to decide which agency you're dealing with and changing the file name to write to each time. This minor change in logic will give you multiple files with the data specific to each agency. It probably isn't perfect, but a great start towards your final solution.
Hogan