Reputation: 3221
I have a string:
C:\Users\O&S-IT\Desktop\NetSparkle (4).txt | C:\Users\O&S-IT\Desktop\NetSparkle (5).txt | C:\Users\O&S-IT\Desktop\NetSparkle (6).txt | C:\Users\O&S-IT\Desktop\NetSparkle (1).txt | C:\Users\O&S-IT\Desktop\NetSparkle (2).txt | C:\Users\O&S-IT\Desktop\NetSparkle (3).txt
I want to be able to extract the 6 filenames from the string without their respective paths into 6 new stings such as:
"NetSparkle (4).txt"
"NetSparkle (5).txt"
"NetSparkle (6).txt"
"NetSparkle (1).txt"
"NetSparkle (2).txt"
"NetSparkle (3).txt"
The deliminator character is always "|". The filenames will always be different as will the paths. The actual number of paths and filenames in the string could be different as well. Sometimes there could be 3 paths/filenames in the string, othertimes there could be as many as 15+.
How would I do this in C# 3.5+?
Upvotes: 1
Views: 287
Reputation: 12458
Here is my suggestion for you:
var stringToExtract = @"C:\Users\O&S-IT\Desktop\NetSparkle (4).txt | C:\Users\O&S-IT\Desktop\NetSparkle (5).txt | C:\Users\O&S-IT\Desktop\NetSparkle (6).txt | C:\Users\O&S-IT\Desktop\NetSparkle (1).txt | C:\Users\O&S-IT\Desktop\NetSparkle (2).txt | C:\Users\O&S-IT\Desktop\NetSparkle (3).txt";
var fullpaths = stringToExtract.Split(new string[] { " | " }, StringSplitOptions.RemoveEmptyEntries);
foreach (var fullpath in fullpaths)
{
var filename = Path.GetFileName(fullpath);
}
Upvotes: 0
Reputation: 7489
This is a quick two-step process.
Step 1: Use string.Split(char)
to get an array of strings. In your case, something along the lines of string[] files = filelist.Split('|');
Step 2: For each string in the array, chop off everything up to the last slash. Example files[i] = files[i].Substring(files[i].LastIndexOf('/') + 1);
I believe you need to +1
to exclude the last slash. If it cuts your file names short, though, just remove it.
Upvotes: 0
Reputation: 160882
var fileNames = input.Split('|')
.Select( x => Path.GetFileName(x))
.ToList();
Or shorter:
var fileNames = input.Split('|')
.Select(Path.GetFileName)
.ToList();
Upvotes: 3
Reputation: 498992
var fileNames = myString.Split('|').Select(s => Path.GetFileName(s));
Upvotes: 2