如何查找含指定字符串的文本文件并加载内容到RichTextBox
Hey there! I'll walk you through both the general approach and the specific example you provided to get this done smoothly (assuming you're working with a WinForms app, since you mentioned a RichTextBox).
Let's break this down into two straightforward steps:
1. Locate the Target Files
Use Directory.EnumerateFiles() to scan your target directory efficiently—it returns files one at a time instead of loading all into memory upfront. You can filter for .txt files and narrow down results to only those whose filenames include your target string.
Key considerations:
- Use
SearchOptionto choose between scanning subdirectories (SearchOption.AllDirectories) or just the top-level folder (SearchOption.TopDirectoryOnly). - Always handle common exceptions (like missing directories, permission restrictions, or locked files) to avoid crashes.
2. Load File Content into RichTextBox
Once you’ve identified matching files, read their content (pay attention to text encoding to prevent garbled text) and populate the RichTextBox. If you’re loading multiple files, add separators between each file’s content to keep things organized.
Given your scenario: name = "test" and directory = @"C:\Users\", here’s a complete code snippet you can use (e.g., in a button click event handler):
using System; using System.IO; using System.Windows.Forms; private void LoadMatchingFilesToRichTextBox() { string targetName = "test"; string targetDirectory = @"C:\Users\"; var outputTextBox = yourRichTextBoxControl; // Replace with your actual RichTextBox name try { // Enumerate all .txt files in the directory and its subfolders foreach (string filePath in Directory.EnumerateFiles(targetDirectory, "*.txt", SearchOption.AllDirectories)) { // Check if filename contains the target string (case-insensitive match) if (Path.GetFileName(filePath).Contains(targetName, StringComparison.OrdinalIgnoreCase)) { // Read file content with UTF-8 encoding (adjust if your files use a different encoding) string fileContent = File.ReadAllText(filePath, System.Text.Encoding.UTF8); // Add content to RichTextBox with a clear separator outputTextBox.AppendText($"--- Content of {Path.GetFileName(filePath)} ---\n"); outputTextBox.AppendText(fileContent); outputTextBox.AppendText("\n\n"); } } // If no files were found, show a message if (string.IsNullOrWhiteSpace(outputTextBox.Text)) { outputTextBox.Text = "No matching text files found in the directory."; } } catch (DirectoryNotFoundException) { MessageBox.Show("The specified directory does not exist."); } catch (UnauthorizedAccessException) { MessageBox.Show("You don't have permission to access this directory."); } catch (Exception ex) { MessageBox.Show($"An unexpected error occurred: {ex.Message}"); } }
Quick Notes on the Code:
StringComparison.OrdinalIgnoreCasemakes the filename match case-insensitive—remove this parameter if you need exact case matching.- Adjust the encoding in
File.ReadAllText()(e.g.,Encoding.ASCII) if your text files use a non-UTF-8 format. - The separator lines (
--- Content of ... ---) help distinguish between content from different files in the RichTextBox.
内容的提问来源于stack exchange,提问作者user9710070

