开发者

Parse DateTime From FileName

Hi I'm trying to develop a utility to manage large sets of backup's:

I have my backups structured like:

D:\SQLBACKUP\NOFAULT2010\Datatbase\LOG\NOFAULT2010_Datatbase_LOG_20110906_182000.trn
D:\SQLBACKUP\NOFAULT2010\Datatbase\LOG\NOFAULT2010_Database_LOG_20110906_183000.trn

I can get rid of the static parts easily enough

Replace(@"D:\SQLB开发者_如何转开发ACKUP\NOFAULT2010\Datatbase\LOG\NOFAULT2010_Datatbase_LOG_", "").Replace(".trn", "");

How can I consistently parse this part 20110906_182000 ... I'm open to any other suggestions. Thanks My brain is on vacation today something terrible.


You can parse out hour, minutes, seconds, etc. with Substring() and then use new DateTime() to create an instance of the date class.

An alternative is to use DateTime.TryParseExact() (http://msdn.microsoft.com/en-us/library/ms131044.aspx)


Just extract the DateTime part of the filename and parse it.

var path = @"D:\SQLBACKUP\NOFAULT2010\Datatbase\LOG\NOFAULT2010_Datatbase_LOG_20110906_182000.trn";
var filename = Path.GetFileNameWithoutExtension(path);
                   // assuming you have a consistent format with a fixed length
var datetimePart = filename.Substring(filename.Length - 15);
var datetime = DateTime.ParseExact(
    datetimePart, "yyyyMMdd_HHmmss", System.Globalization.CultureInfo.InvariantCulture);

p.s., When working with path strings, always use the System.IO.Path class to manipulate them. Don't use regular string manipulation techniques.


For your case you don't actually need to use substring or string parsing.

        DateTime parsedFileDate;

        string FileFullPath = @"D:\SQLBACKUP\NOFAULT2010\Datatbase\LOG\NOFAULT2010_Database_LOG_20110906_183000.trn";
        string FileNameFormat = "'NOFAULT2010_Database_LOG_'yyyyMMdd_HHmmss'.trn'";

        DateTime.TryParseExact(Path.GetFileName(FileFullPath), FileNameFormat, null, System.Globalization.DateTimeStyles.None, out parsedFileDate);

        Console.WriteLine($"Parsed date: {parsedFileDate}");

        Console.ReadLine();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜