更多的路径等 [英] More of paths and such

查看:179
本文介绍了更多的路径等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个脚本,找到路径中的第二个文件夹,我该怎么做?

I am making a script that finds what the 2nd folder in the path is, how would I do this?

dirA

dirB / C ----我需要dirB

indirB - dirD / E

indirE - 文件

dirA
dirB/C ---- I need dirB
indirB - dirD/E
indirE - The file

我需要找到文件夹的名称在第二级文件路径(我用星星标记)。

I need to find the name of the folder in the 2nd level that paths to the file (I marked it with stars).

我将如何找到这个

推荐答案

此扩展程序如何:

public static class StringExtensions
{
    public static String PathLevel(this String path, int level)
    {
        if (path == null) throw new ArgumentException("Path must not be null", "path");
        if (level < 0) throw new ArgumentException("Level must be >= 0", "level");

        var levels = path.Split(Path.DirectorySeparatorChar);
        return levels.Length > level ? levels[level] : null;
    }
}

测试:

var path = @"C:\Temp\Level2\Level3\Level4\File.txt";
var secondLevel = path.PathLevel(2); // => "Level2"

它将路径分割为 DirectorySeparatorChar 串[]
你想要第二级(第三个元素),这返回Level2。请注意,第一个元素是 C:

It splits the path by DirectorySeparatorChar to a String[]. You wanted the second level(the third element), this returns "Level2". Note that the first element is C:.

这篇关于更多的路径等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆