如何根据文件夹拆分文件路径

时间:2017-02-16 09:57:58

标签: c#

例如,我有file1.txt,以下是文件的内容

test1\abc\a.xml
test1\abc\n.cs
test1\HB\proc1\candidate1\rel1\spy\can.xml
test1\HB\proc1\candidate1\rel1\spy\globals.xml
test1\HB\proc1\candidate1\rel1\spy\mike.cs

现在逐行阅读上面的文件想创建另一个文件..say文件2,内容如下

test1\abc
test1\abc\a.xml
test1\abc\n.xml
test1\HB
test1\HB\proc1
test1\HB\proc1\candidate1
test1\HB\proc1\candidate1\rel1
test1\HB\proc1\candidate1\rel1\spy
test1\HB\proc1\candidate1\rel1\spy\can.xml
test1\HB\proc1\candidate1\rel1\spy\globals.xml
test1\HB\proc1\candidate1\rel1\spy\mike.cs

2 个答案:

答案 0 :(得分:1)

所以你可以用一种相当简单的方式列举这样:

public static IEnumerable<string> EnumerateAllPaths(string[] input)
{
    var hs = new HashSet<string>();

    foreach(var s in input)
    {
        var parts = s.Split(new[]{@"\"},StringSplitOptions.None);

        for(var i = 0;i<parts.Length;i++)
        {
            var section = String.Join(@"\", parts.Take(i+1));
            if(hs.Add(section))
                yield return section;
        }

    }
}

要从原始文件中获取单独的行,您可以使用ReadAllLines

实例:http://rextester.com/YBOGIH60970

答案 1 :(得分:0)

我认为这样做非常复杂......

var filenames = File.ReadLines("source.txt");
var result = ExpandFilenames(filenames);
File.WriteAllLines("dest.txt", result);

然后:

static IEnumerable<string> ExpandFilenames(IEnumerable<string> filenames) {
    var alreadyDone = new HashSet<string>();

    foreach (string fileName in filenames) {
        string directoryName = Path.GetDirectoryName(fileName);

        // "Expand" the parent directories
        var expandedDirectories = ExpandDirectories(directoryName, alreadyDone);

        foreach (string dir in expandedDirectories) {
            yield return dir;
        }

        yield return fileName;
    }
}

// Recursive yield :-) I do know it is slow, but it is easy to write :-)
static IEnumerable<string> ExpandDirectories(string directoryName, HashSet<string> alreadyDone) {
    if (directoryName == string.Empty || alreadyDone.Contains(directoryName)) {
        yield break;
    }

    // We "cheat": we use Path.GetDirectoryName to get the name of 
    // the "parent" directory
    string directoryName2 = Path.GetDirectoryName(directoryName);

    if (directoryName2 != null) {
        var expandedDirectories = ExpandDirectories(directoryName2, alreadyDone);

        foreach (string dir in expandedDirectories) {
            yield return dir;
        }
    }

    alreadyDone.Add(directoryName);
    yield return directoryName;
}

请注意,我将IEnumerable<>作为来源和目的地,我使用接受File.ReadLines的{​​{1}} / File.WriteAllLines重载