目录树数组的路径

时间:2012-04-26 17:48:05

标签: c# directory

我正在使用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;
  }
}

1 个答案:

答案 0 :(得分: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);