这样的事情应该对你有用。它没有经过测试,但是除了移动文件之外,它还应该注意解析文件名并创建整个存档目录树。
Archive() 方法返回一个布尔值,表示指定的文件是否被移动。
您可能需要调整正则表达式,因为它基于我对文件名格式的错误理解。
private static void ArchiveAll( DirectoryInfo dropDirectory , DirectoryInfo archiveRoot )
{
foreach ( FileInfo file in dropDirectory.EnumerateFiles("*.xls") )
{
Archive( file , archiveRoot ) ;
}
}
private static bool Archive( FileInfo file , DirectoryInfo archiveRoot )
{
bool wasArchived = false ;
Match m = rxFileNamePattern.Match(file.Name) ;
if ( m.Success )
{
string pfx = m.Groups["prefix"].Value ;
string sfx = m.Groups["suffix"].Value ;
string dtRaw = m.Groups["timestamp"].Value ;
DateTime dt = DateTime.ParseExact( dtRaw , "yyMMddHHmm" , CultureInfo.CurrentCulture ) ;
string path = Path.Combine( "." ,
pfx ,
dt.ToString( "yyyy" ) ,
sfx ,
dt.ToString( "MMMM" ) ,
dt.ToString( "dd" ) ,
dt.ToString( "HH00" ) ,
dt.ToString( "00mm" )
) ;
DirectoryInfo archive = archiveRoot.CreateSubdirectory( path ) ;
file.MoveTo( Path.Combine( archive.FullName , file.Name ) ) ;
wasArchived = true ;
}
return wasArchived ;
}
const string fnPattern = @"
^ # - start of text, followed by
(?<prefix> \p{Ll}+) # - prefix : 1 or more lowercase letters, followed by
(?<suffix> \p{Lu}+ ) # - suffix : 1 or more uppercase letters, followed by
(?<timestamp> \d{10} ) # - timestamp : 10 decimal digits in the form YYMMDDhhmm, followed by
(?<seconds> \d{4} ) # - seconds : 4 decimal digits
(?<ext> \.xls ) # - ext : the literal '.xls'
$ # - end of text.
" ;
const RegexOptions fnPatternOptions = RegexOptions.IgnoreCase
| RegexOptions.IgnorePatternWhitespace
| RegexOptions.ExplicitCapture
;
static readonly Regex rxFileNamePattern = new Regex( fnPattern , fnPatternOptions ) ;