样本文件名:S012311d130614t095121.14194092001
左边的第九个字符是日期(130614)然后我想根据日期将此文件存储在以下目录中:
1306/ (year-month)
130614/ (year-month-day)
S012311d130614t095121.14194092001
样本文件名:S012311d130614t095121.14194092001
左边的第九个字符是日期(130614)然后我想根据日期将此文件存储在以下目录中:
1306/ (year-month)
130614/ (year-month-day)
S012311d130614t095121.14194092001
如果我理解正确:
string input = Path.GetFileName(originalFile);
//"S012311d130614t095121.14194092001";
string yearMonthDay = input.Substring(8, 6);
string yearMonth = yearMonthDay.Substring(0, 4);
Console.WriteLine(yearMonth);
string folder = Path.Combine(Path.Combine(rootFolder, yearMonth), yearMonthDay);
Directory.CreateDirectory(folder);
// Write to folder
File.Copy(originalFile, Path.Combine(folder, input);
这将保证在rootFolder
with下存在一个文件夹1306\130614
,并为您提供创建文件夹的文件夹名称。
DateTime
首先,从文件名中获取值的扩展方法:
public static class FileInfoHelpers
{
private static Regex rxIso8601DateTimeValue = new Regex( @"\d{6,6}[Tt]\d{6,6}(\.\d+)$");
private static readonly string[] formats = new string[]{
@"yyMMdd\tHHmmss.fffffff" ,
@"yyMMdd\THHmmss.fffffff" ,
} ;
public static DateTime? TimestampFromName( this FileInfo fi )
{
DateTime? value = null ;
Match m = rxIso8601DateTimeValue.Match( fi.Name ) ;
if ( m.Success )
{
DateTime dt ;
bool success = DateTime.TryParseExact( m.Value , formats , CultureInfo.InvariantCulture , DateTimeStyles.None , out dt ) ;
value = success ? dt : (DateTime?)null ;
}
return value ;
}
}
那么你只需要这样的东西:
// establish the source and target directories
// ensuring that they both exist
DirectoryInfo source = Directory.CreateDirectory( @"C:\some\directory\with\files\to\move" ) ;
DirectoryInfo target = Directory.CreateDirectory( @"C:\repository" ) ;
// save the current working directory
string prevCwd = Environment.CurrentDirectory ;
try
{
// make the destination root the current working directory
Environment.CurrentDirectory = target.FullName ;
// enumerate over the files in the source directory
foreach ( FileInfo fi in source.EnumerateFiles() )
{
// parse a datetime out of the file name
DateTime? timestamp = fi.TimestampFromName() ;
// if we didn't find a valid datetime value in the file name, skip this file
if ( !timestamp.HasValue ) continue ;
// construct the relative path of the archive subdirectory
// and ensure that it exists
string relativeSubdir = timestamp.Value.ToString("yyMM\\yyMMdd") ;
DirectoryInfo subdir = target.CreateSubdirectory( relativeSubdir ) ;
// build a relative path to the file's desired location
// and move it there.
string destination = Path.Combine( relativePath , fi.Name ) ;
fi.MoveTo( destination ) ;
}
}
finally
{
// restore the original CWD
Environment.CurrentDirectory = prevCwd ;
}
简单的!
您可以使用以下代码获取目录中的所有文件(文件名):
string[] filePaths = Directory.GetFiles(@"Directory");
然后使用 for-each 获取每个字符串一个该字符串数组并检查每个字符串的第九个字符(我不会为此发布代码,对你来说有点工作)
使用以下代码复制您的文件:
System.IO.File.Copy(originFile, destFile, true);
结合所有这些以实现您的目标。