目录树数组中的路径

本文关键字:路径 数组 目录树 | 更新日期: 2023-09-27 18:32:25

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

这是我所拥有的:

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

目录树数组中的路径

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