簡體   English   中英

如何從目錄字符串中僅獲取最后的子目錄名稱和文件名?

[英]How can i get from a directory string only the last subdirectory name and the file name?

我有這一行,如何僅獲取最后的子目錄名稱和文件名?

    label13.Text = Path.GetFileName(file1);

我只獲得文件名:test.avi如果我不僅使用Path.GetFileName file1,我將得到類似以下內容:

http://users/test/test/program/test/test.avi

我想得到的是最后一個子目錄名稱:test和文件名:test.avi因此在label13中我將看到:test / test.avi

我該怎么做 ?

只使用Path

Path.Combine(Path.GetFileName(Path.GetDirectoryName(path)), Path.GetFileName(path))

您還可以拆分字符串並獲取結果數組的最后2個元素:

string path = "http://users/test/test/program/test/test.avi";
var elements = path.Split('/');
string result = elements[elements.Length-1] + "/" + elements[elements.Length];
System.Console.WriteLine(result);

您可以使用以下擴展方法來檢索到路徑分隔符的倒數第二個索引的字符索引,並返回正確的子字符串:

using System;
using System.Linq;

public static class StringExtensions
{
    public static int NthLastIndexOf(this string value, char c, int n = 1)
    {
        if (count < 1)
        {
            throw new ArgumentOutOfRangeException("count must be greater than 0.");
        }

        var index = 1;
        for (int i = value.Length - 1; i >= 0; i--)
        {
            if (value[i] == c)
            {
                if (index == n)
                {
                    return i;
                }
                index++;
            }
        }
        return -1;
    }
}

class Program
{
    public static string GetEndOfPath(string path)
    {
        var idx = path.NthLastIndexOf('/', 2);
        if (idx == -1)
        {
            throw new ArgumentException("path does not contain two separators.");
        }

        return path.Substring(idx + 1);
    }

    static void Main()
    {
        var result = GetEndOfPath("http://users/test/test/program/test/test.avi");
        Console.WriteLine(result);
    }
}

擴展方法NthLastIndexOf返回指定的Unicode字符的倒數第n個從零開始的索引位置。 如果在字符串中至少n次未找到該字符,則該方法返回-1。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM