Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# DateTime.ParseExact with backslashes in format

Tags:

c#

datetime

I've got some sub directories that are named with dates like so:

C:\SomeDirectory\201309\01
C:\SomeDirectory\201309\02
C:\SomeDirectory\201309\03
C:\SomeDirectory\201309\04
C:\SomeDirectory\201309\05

etc.

What I'm trying to do is get the directory listing and then use Linq to limit my results based on a date range.

I've got it working like so:

string path = @"C:\SomeDirectory";
DateTime f = new DateTime(2013, 9, 1);
DateTime t = new DateTime(2013, 9, 3);
DateTime dt;
var dirs =
    Directory.GetDirectories(path, "*.*", SearchOption.AllDirectories)
             .Where(d => DateTime.TryParseExact(
                 d.Substring(Math.Max(0, d.Length - 9)).Replace("\\", null),
                 "yyyyMMdd",
                 CultureInfo.Invarient,
                 DateTimeStyles.None,
                 out dt)
                 && f <= dt
                 && dt <= t);

I would, however, like to change the TryParseExact portion so that I don't have to replace the backslash - like so:

DateTime.TryParseExact(
    d.Substring(Math.Max(0, d.Length - 9)),
    @"yyyyMM\dd",
    CultureInfo.Invarient,
    DateTimeStyles.None,
    out dt)

But, it seems TryParseExact does not like that format. I was thinking this may have something to do with the CultureInfo - but I was unable to track down a possible solution to help me with the backslash.

Any assistance would be greatly appreciated!

like image 267
Sean Hosey Avatar asked Mar 20 '26 20:03

Sean Hosey


1 Answers

According to Custom Date and Time Format Strings on MSDN \ is an escape character. So in @"yyyyMM\dd" it removed special meaning from first d. You should escape the \ instead:

To include a backslash in a result string, you must escape it with another backslash (\\).

So try following:

DateTime.TryParseExact(
    d.Substring(Math.Max(0, d.Length - 9)),
    @"yyyyMM\\dd",
    CultureInfo.InvariantCulture,
    DateTimeStyles.None,
    out dt)
like image 63
MarcinJuraszek Avatar answered Mar 22 '26 10:03

MarcinJuraszek