C#控制台应用程序,根据文件名将文件移动到特定目录

本文关键字:移动 文件 应用程序 控制台 文件名 | 更新日期: 2023-09-27 18:27:46

样本文件名:S012311d130614t095121.14194092001

左边的第九个字符是日期(130614),然后我想根据日期将此文件存储在以下目录中:

1306/         (year-month)
  130614/     (year-month-day)
    S012311d130614t095121.14194092001

C#控制台应用程序,根据文件名将文件移动到特定目录

如果我理解正确:

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);

这将保证rootFolder1306'130614下存在一个文件夹,并为您提供创建文件夹的文件夹名称。

您可以使用以下代码获取目录中的所有文件(文件名):

string[] filePaths = Directory.GetFiles(@"Directory");

然后使用for each为每个字符串获取一个该字符串数组,并检查每个字符串的第九个字符(我不会为此发布代码,为您做一些工作)

使用以下代码复制您的文件:

System.IO.File.Copy(originFile, destFile, true);

把所有这些结合起来实现你的目标。

首先,一个从文件名中获取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 ;
}

轻松!