如何从多行SelectedFileText中提取所有文件名而非仅最后一个?
Solution to Extract All Filenames from Multi-Line Paths
Got it, let's fix this so you can grab every filename from those multi-line paths. Here's how to do it step by step:
- Split the input into individual lines: First, we need to break that multi-line text into separate path strings. Using
Environment.NewLineensures we handle line breaks correctly across different operating systems, and we'll skip any empty lines to avoid errors. - Process each line: For every valid path line, use
Path.GetFileName()to extract just the filename—this method is way more reliable than splitting on backslashes because it handles all path separator types and edge cases automatically. - Collect all filenames: Store each extracted filename in a list (or array) so you can use them however you need.
Here's the updated code:
using System.IO; using System.Collections.Generic; // Get the multi-line text from your control string allPathText = SelectedFileText.Text; // Split into individual lines, ignoring empty ones string[] pathLines = allPathText.Split( new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries ); // List to hold all extracted filenames List<string> allFilenames = new List<string>(); foreach (string line in pathLines) { // Trim any extra whitespace from the line (in case of leading/trailing spaces) string cleanedPath = line.Trim(); // Skip any lines that are empty after trimming if (!string.IsNullOrEmpty(cleanedPath)) { // Extract the filename using Path.GetFileName string filename = Path.GetFileName(cleanedPath); allFilenames.Add(filename); } } // If you need an array instead of a list, convert it: string[] filenamesArray = allFilenames.ToArray();
This will give you a list containing text.css and multiple.php (and any other filenames from your input lines). The Path.GetFileName() method takes care of all the path parsing work for you, so you don't have to worry about splitting on the right character or handling nested directories.
内容的提问来源于stack exchange,提问作者Fuppetia
相关产品推荐
相关产品推荐

