我有一些以日期命名的子目录,例如:
C:\SomeDirectory\201309\01
C:\SomeDirectory\201309\02
C:\SomeDirectory\201309\03
C:\SomeDirectory\201309\04
C:\SomeDirectory\201309\05
我想要做的是获取目录列表,然后使用Linq根据日期范围限制结果。
我已经这样使它工作:
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);
然而,我希望更改TryParseExact部分,以便我不必替换反斜杠 - 就像这样:
DateTime.TryParseExact(
d.Substring(Math.Max(0, d.Length - 9)),
@"yyyyMM\dd",
CultureInfo.Invarient,
DateTimeStyles.None,
out dt)
但是,似乎TryParseExact不喜欢那种格式。我认为这可能与CultureInfo有关 - 但我无法找到可能帮助我处理反斜杠的解决方案。
非常感谢您的任何帮助!
DateTime
格式化使用的特殊字符,我相信。更多信息请参见此处。 - Adam HouldsworthSomeDirectory
下的单个目录中搜索?或者您可以先检查:Where(d=>d.Length==6 && d.All(Char.IsDigit))
。 - Tim Schmelter