开发者

Extract multiple filenames from multiple paths into multiple strings

I have a string:

C:\Users\O&S-IT\Desktop\NetSparkle (4).txt | C:\Users\O&S-IT开发者_如何学Go\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+?


var fileNames = input.Split('|')
                     .Select( x => Path.GetFileName(x))
                     .ToList();

Or shorter:

var fileNames = input.Split('|')
                     .Select(Path.GetFileName)
                     .ToList();


var fileNames = myString.Split('|').Select(s => Path.GetFileName(s));


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.


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);
        }


String.Split will do the trick.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜