I have a file on which I want to replace the dates but I don’t know what dates are on it and I want to do generic code for me to use the same executable for other files.
I put all content of the file in a string and I want to replace all dates with format dd/mm/yyyy (ex: 19/12/2011) with the actual date (20/12/2011).
How can I do that?
Code so far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ReplaceDates
{
class Program
{
static int Main(string[] args)
{
string FileIn = retreiveArgument(args, "i");
int AddDays = Int32.Parse(retreiveArgument(args, "d"));
string date = (System.DateTime.Now).AddDays(AddDays).ToString("dd/MM/yyyy");
string content = "", date2replace = "";
if (File.Exists(FileIn))
{
File.Copy(FileIn, FileIn + ".bkp", true);
try
{
content = File.ReadAllText(FileIn);
// here is what I need to do
}
catch (Exception)
{
Console.WriteLine("Error replacing dates in " + FileIn + ".");
return 0;
}
try
{
File.WriteAllText(FileIn, content);
Console.WriteLine("Dates replaced in " + FileIn + ".");
return 0;
}
catch (Exception)
{
Console.WriteLine("Couldn't write the file " + FileIn);
return 2;
}
}
else
{
Console.WriteLine("File " + FileIn + " does not exist.");
return 1;
}
}
private static string retreiveArgument(string[] argument, string argumentName)
{
for (int i = 0; i < argument.Length; i++)
{
if (argument[i].ToLower().Equals("-h") || argument[i].ToLower().Equals("help") || argument[i].ToLower().Equals("-help") || argument[i].Equals("?") || argument[i].Equals("-?"))
{
Console.WriteLine("Usage : ");
Console.WriteLine("ReplaceDates.exe -i [Input File] -d [Addition]");
Console.WriteLine("[Input File] -> Complete path to the file.");
Console.WriteLine("[Addition] -> Adds the specified value in days to the actual date.");
Console.WriteLine();
Console.WriteLine("This executable replaces the data from the input file.");
}
else
{
if (argument[i].Equals("-" + argumentName))
{
return argument[i + 1].Trim();
}
}
}
return "";
}
}
}
Here’s a solution using a MatchEvaluator. Tweak the regular expression if desired;