Hi guys,

I have a number of files within a directory which are named Log-2014-01-21.txt and similar. What I’m trying to do is write a program that will archive these files based on the month that is in the file name rather than the file Info. The part I’m struggling with is getting the date out of the string which will work for different string lengths i.e if the file was called error-log-2014-11-11.txt. Is there a nice way of doing a string spilt to accomplish this, or another method?

Kind Regards

The string Split method can be used here.
Works like this:
string[] splits = FileName.Split(new Char[]{'-'});
See for further details here.

The part I’m struggling with is getting the date out of the string which will work for different string lengths

So here's my thought process as a professional (as if that adds weight to my comments...):

  1. Is the date always in the same place (ie. at the end of the file name before the path?)
  2. Is the file name always formatted the same way?
  3. Is the date formatted the same way in all cases?
  4. Does the date format always have the same number of characters?

The answer to those questions changes the solution. It could be as simple as this:

private DateTime ExtractDate(string path)
{
    var file = Path.GetFileNameWithoutExtension(path);
    var fileDate = file.Substring(file.Length - 10);

    return DateTime.Parse(fileDate);
}

But this code smells funny, and I'd definitely ask about it in a code review, because it seems brittle in the presence of variations of the date format.

A better approach might be using a robust regular expression to find a date at the end of the string, then parse that. But if there's a format guarantee then this approach would be unnecessarily complex.

This article has been dead for over six months. Start a new discussion instead.