My thought would be to create a file in the target folder that defines the mapping between the Company Code in the HD_nnnn.txt file and the required date formatting:
00098,MMDDYYYY
50,YYYYDDMM
That way adding more Company Codes doesn't require modifying the program code...
This compares the Company Code from the HD_nnnn.txt files
as strings (
i.e., 050 is not the same as 50) and assumes no extraneous characters around that piece of data (and having a tab or comma to delimit it from any following text).
So here's an
almost complete solution. (more error handling required...)
using System;
using System.Collections.Generic;
using System.IO;
namespace ConsoleApplication23
{
class Program
{
const string FormatMapFilename = "FormatMap.txt";
static Dictionary<string, string> CompanyFormatMap = new Dictionary<string, string>();
static string WorkingPath = @"D:\Temp\";
static void Main(string[] args)
{
if (!LoadFormatMap())
return;
foreach (string hdFilename in Directory.GetFiles(Path.Combine(WorkingPath, "HD_*.txt")))
{
ProcessFileGroup(hdFilename);
}
}
static bool LoadFormatMap()
{
foreach (var line in File.ReadLines(Path.Combine(WorkingPath, FormatMapFilename)))
{
string[] mapping = line.Split('\t', ',');
if (mapping.Length >= 2)
{
CompanyFormatMap.Add(mapping[0], mapping[1]);
}
else
{
Console.Error.WriteLine("Invalid line in: " + FormatMapFilename);
return false;
}
}
return true;
}
static void ProcessFileGroup(string hdFilename)
{
string folder = Path.GetDirectoryName(hdFilename);
string extension = Path.GetExtension(hdFilename);
string fileDigits = Path.GetFileNameWithoutExtension(hdFilename).Split('_')[1];
string dateFormat = null;
using (var hdFile = new StreamReader(hdFilename))
{
string[] splitLine = hdFile.ReadLine().Split('\t', ',');
if (!CompanyFormatMap.TryGetValue(splitLine[0], out dateFormat))
{
Console.Error.WriteLine("Unrecognized company code in: " + hdFilename);
return;
}
}
string filedate = DateTime.Today.ToString(dateFormat);
int digitsCount = fileDigits.Length;
foreach (string filePath in Directory.GetFiles(Path.Combine(folder, "*_", fileDigits, extension)))
{
string filename = Path.GetFileNameWithoutExtension(filePath);
filename = filename.Substring(0, filename.Length - digitsCount) + filedate;
File.Move(filePath, Path.Combine(folder, filename, extension));
}
}
}
}