0

Directory.GetFiles用来查找将被复制的文件。我需要找到文件的路径,以便我可以使用副本,但我不知道如何找到路径。它可以很好地遍历文件,但我无法复制或移动它们,因为我需要文件的源路径。

这就是我所拥有的:

string[] files = Directory.GetFiles(sourcePath, "*.*", SearchOption.AllDirectories);

System.Console.WriteLine("Files Found");

// Display all the files.
foreach (string file in files)
{
  string extension = Path.GetExtension(file);
  string thenameofdoom = Path.GetFileNameWithoutExtension(file);
  string filename = Path.GetFileName(file);

  bool b = false;
  string newlocation = (@"\\TEST12CVG\Public\Posts\Temporaryjunk\");

  if (extension == ".pst" || 
    extension == ".tec" || 
    extension == ".pas" || 
    extension == ".snc" || 
    extension == ".cst")
  {
    b = true;
  }

  if (thenameofdoom == "Plasma" || 
    thenameofdoom == "Oxygas" || 
    thenameofdoom == "plasma" || 
    thenameofdoom == "oxygas" || 
    thenameofdoom == "Oxyfuel" || 
    thenameofdoom == "oxyfuel")
  {
    b = false;
  }

  if (b == true)
  {
    File.Copy(file, newlocation + thenameofdoom);
    System.Console.WriteLine("Success: " + filename);
    b = false;
  }
}
4

1 回答 1

1

Path.GetFullPath工作,但也考虑使用FileInfo许多文件帮助方法。

我会使用与此类似的方法(可以使用更多的错误处理(尝试捕获...),但这是一个好的开始

编辑我注意到您正在过滤掉扩展,但需要它们,更新代码允许这样做

class BackupOptions
{
  public IEnumerable<string> ExtensionsToAllow { get; set; }
  public IEnumerable<string> ExtensionsToIgnore { get; set; }
  public IEnumerable<string> NamesToIgnore { get; set; }
  public bool CaseInsensitive { get; set; }

  public BackupOptions()
  {
    ExtensionsToAllow = new string[] { };
    ExtensionsToIgnore = new string[] { };
    NamesToIgnore = new string[] { };
  }
}

static void Backup(string sourcePath, string destinationPath, BackupOptions options = null)
{

  if (options == null)
    optionns = new BackupOptions();

  string[] files = Directory.GetFiles(sourcePath, ".", SearchOption.AllDirectories);
  StringComparison comp = options.CaseInsensitive ? StringComparison.CurrentCultureIgnoreCase : StringComparison.CurrentCulture;

  foreach (var file in files)
  {
    FileInfo info = new FileInfo(file);

    if (options.ExtensionsToAllow.Count() > 0 &&
      !options.ExtensionsToAllow.Any(allow => info.Extension.Equals(allow, comp)))
      continue;

    if (options.ExtensionsToIgnore.Any(ignore => info.Extension.Equals(ignore, comp)))
        continue;

    if (options.NamesToIgnore.Any(ignore => info.Name.Equals(ignore, comp)))
      continue;

    try
    {
      File.Copy(info.FullName, destinationPath + "\\" + info.Name);
    }
    catch (Exception ex)
    {
      // report/handle error
    }
  }
}

像这样的电话:

var options = new BackupOptions
{
  ExtensionsToAllow = new string[] { ".pst", ".tec", ".pas", ".snc", ".cst" },
  NamesToIgnore = new string[] { "Plasma", "Oxygas", "Oxyfuel" },
  CaseInsensitive = true
};

Backup("D:\\temp", "D:\\backup", options);
于 2012-04-26T18:12:17.157 回答