Reputation: 136
I need to capture a substring for each item in a list of filepaths. The list I am looping through does not exist in the file system, so I cannot use the Path class. I want to begin parsing from the end of the string and stop once I reach the first "/". I've tried .Substring() and .Split() but neither method appears to have the ability to match a specified pattern or read from right to left.
Example: Some Directory/Some SubDirectory/SomeFile.pdf
I want to capture "SomeFile.pdf"
Upvotes: 2
Views: 644
Reputation: 1140
Path.GetFileName(path)
Using the Path class is the simplest, most correct and secure way. However, if you would like to parse from the end of the string, or from right to left, one way is to reverse the string and parse it.
Reverse the string, search for "/", get the substring, reverse your substring, and you have what you were looking for.
Example: Call the method GetFileNameFromPath with your path, and it will print SomeFile.pdf.
using System;
public class Test
{
public static void Main()
{
string path = "Some Directory/Some SubDirectory/SomeFile.pdf";
string fileName = GetFileNameFromPath(path);
Console.WriteLine(fileName);
}
public static string GetFileNameFromPath(string path)
{
string fileName = string.Empty;
path = path.ReverseString();
fileName = path.Substring(0, path.IndexOf(@"/"));
fileName = fileName.ReverseString();
return fileName;
}
}
public static class StringExtension
{
public static string ReverseString(this string s)
{
char[] arr = s.ToCharArray();
Array.Reverse(arr);
return new string(arr);
}
}
Upvotes: 0
Reputation: 460108
You should use the Path
class instead.
for example:
string path = "Some Directory/Some SubDirectory/SomeFile.pdf";
string fileName = System.IO.Path.GetFileName(path);
Edit: just to answer you original question how to "read from right to left":
You can use String.Substring
with String.LastIndexOf
:
string fileName = path.Substring(path.LastIndexOf("/") + 1);
(However, use the Path
class if you work with paths)
Upvotes: 10
Reputation: 19367
Using Path is best if you are actually treating it as file/folder information, but if you are treating it as a string that you just happen to want to split at '/' then you could Split then Reverse:
string str = "Some Directory/Some SubDirectory/SomeFile.pdf";
string[] terms = str.Split('/');
Array.Reverse(terms);
foreach (string term in terms)
{
Console.WriteLine(term);
}
Upvotes: 0