更新我假设 FTP 列表的文件显示有一个固定的结构,所以你可以简单地使用String.Substring
来提取日期时间字符串,然后解析DateTime.ParseExact
:
var s = "-rwxr-xr-x 1 ftp ftp 267662 Jun 06 09:13 VendorInventory_20130606_021303.txt\r";
var datetime = DateTime.ParseExact(s.Substring(72,15),"yyyyMMddHHmmss",null);
原始答案
使用正则表达式。尝试以下操作:
var s = "-rwxr-xr-x 1 ftp ftp 267662 Jun 06 09:13 VendorInventory_20130606_021303.txt\r";
/*
The following pattern means:
\d{8}) 8 digits (\d), captured in a group (the parentheses) for later reference
_ an underscore
(\d{6}) 6 digits in a group
\. a period. The backslash is needed because . has special meaning in regular expressions
.* any character (.), any number of times (*)
\r carriage return
$ the end of the string
*/
var pattern = @"(\d{8})_(\d{6})\..*\r$";
var match = Regex.Match(s, pattern);
string dateString = matches.Groups[1].Value;
string timeString = matches.Groups[2].Value;
并使用解析ParseExact
:
var datetime = DateTime.ParseExact(dateString + timeString,"yyyyMMddHHmmss",null);