I have this line and how can I get only the last subdirectory name and the file name ?
label13.Text = Path.GetFileName(file1);
Im getting only the file name: test.avi If im not using the Path.GetFileName only file1 I will get something like:
http://users/test/test/program/test/test.avi
What I want to get is the last subdirectory name wich is: test and the file name: test.avi So in label13 I will see: test/test.avi
How can I do it ?
只使用Path
:
Path.Combine(Path.GetFileName(Path.GetDirectoryName(path)), Path.GetFileName(path))
You can also split the string and grab the last 2 elements of the resulting array:
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);
You can use the following extension method to retrieve the character index to the nth-last index of the path separator and the return the correct substring:
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);
}
}
The extension method NthLastIndexOf
returns the zero-based index position of the nth-last occurrence of a specified Unicode character. The method returns -1 if the character is not found at least n times in the string.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.