c# - 递归地遍历目录并处理相对路径

标签 c# .net

我有一个文本文件,其中包含不同文本文件的路径以及路径等。像这样:

C:\folder1\dirs1.txt:
           folder2\dirs1.txt
           folder2\dirs2.txt
           folder3\dirs1.txt

C:\folder1\folder2\dirs1.txt:
           folder4\dirs1.txt
           folder4\dirs2.txt     

我需要遍历所有文件并打印它,这很简单:

IEnumerable<string> ExtractAllPathsFromFile(string path) { ... } 

void PrintAllPaths(string root)
{
      var paths = ExtractAllPathsFromFile(root);

      foreach (path in paths)
      {
         Console.WriteLine(path);
         if (File.Exists(path))
            PrintAllPaths(path);
      }
}



PrintAllPaths(root:C:\folder1\dirs1.txt);

但是正如您在示例中看到的,所有路径都是相对的(不是绝对的),我需要想出如何在我的算法中处理它的想法。

最佳答案

使用Path.Combine()方法安全地连接多个路径。您可以使用 Path.GetDirectoryName() 方法从 C:\folder1\dirs1.txt 获取目录路径。这样的事情行不通吗?

using System.IO;

public static string[] ExtractPathsFromFile(string originalPath)
{
    string[] newPaths = File.ReadAllLines(originalPath);
    string[] modified = new string[newPaths.Length];
    for (int i = 0; i < newPaths.Length; i++)
        modified[i] = Path.Combine(Path.GetDirectoryName(originalPath), newPaths[i].Trim());
    return modified;
}

关于c# - 递归地遍历目录并处理相对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32434920/

相关文章:

jquery - 使用jquery跨域webmethod调用

c# - 关于经典 MVC 的问题

c# - 当编写ASPX时,在aspx本身中使用html是不明智的吗?

c# - IsDirty 对 EF 实体使用 INotifyPropertyChanged

c# - 检测 WPF 中的系统语言更改

.net 框架 3.5 源代码

c# - 在使用 IoC 的 c#.Net 中,不使用构造函数直接将依赖项传递给方法是否可以?

c# - 请说明如何在.Net 4.6中使用EventListener类

c# - 安全序列化

.net - Observable.Timer() 会导致内存泄漏吗?