如何从项目资源中读取并编辑TXT文件,以及实现将TXT文件内容读取到变量的技术求助
Hey there! Let's walk through how to properly read text files from your project resources into a variable, plus how to read and edit those files—starting with your existing code.
First: Check Your File's Project Settings
Your current code uses AppDomain.CurrentDomain.BaseDirectory to get the app's runtime folder, then combines it with your Base/base.txt path. For this to work, you need to make sure your text file is copied to the output directory when you build:
- Right-click
Base/base.txtin your project → Properties - Set Copy to Output Directory to Copy if newer or Copy always
- This ensures the file exists in the
Basesubfolder of your executable's directory after building.
1. Read Project TXT File to a Variable
Option 1: As a Content File (Your Current Approach)
Here's an improved version of your code with error handling and clarity:
try { var exePath = AppDomain.CurrentDomain.BaseDirectory; var path = Path.Combine(exePath, "Base", "base.txt"); // Using separate args is cleaner // Optional: Verify the path exists first if (!File.Exists(path)) { Console.WriteLine($"File not found at: {path}"); return; } // Read content (specify encoding if your file uses non-UTF-8, e.g. GB2312) string contents = File.ReadAllText(path, Encoding.UTF8); Console.WriteLine("File content loaded successfully!"); // Use 'contents' variable here } catch (IOException ex) { Console.WriteLine($"Error reading file: {ex.Message}"); }
Option 2: As an Embedded Resource (No Separate File)
If you want to bundle the text file directly into your assembly (so it's not a separate file after build):
- Right-click
Base/base.txt→ Properties → Set Build Action to Embedded Resource - Use this code to read it:
try { var assembly = Assembly.GetExecutingAssembly(); // Resource name format: [YourProjectNamespace].Base.base.txt (check your project's namespace) var resourceName = "YourProjectName.Base.base.txt"; using (Stream stream = assembly.GetManifestResourceStream(resourceName)) { if (stream == null) { Console.WriteLine($"Embedded resource not found: {resourceName}"); return; } using (StreamReader reader = new StreamReader(stream)) { string contents = reader.ReadToEnd(); Console.WriteLine("Embedded resource loaded successfully!"); // Use 'contents' variable here } } } catch (IOException ex) { Console.WriteLine($"Error reading embedded resource: {ex.Message}"); }
Note: To find the exact resource name, use assembly.GetManifestResourceNames() to list all embedded resources.
2. Read & Edit the TXT File
To modify the file, you'll read its content, make changes, then write it back. Here's a safe way to do this (handling file locks and encoding):
try { var exePath = AppDomain.CurrentDomain.BaseDirectory; var path = Path.Combine(exePath, "Base", "base.txt"); if (!File.Exists(path)) { Console.WriteLine($"File not found at: {path}"); return; } // Step 1: Read the content string contents = File.ReadAllText(path, Encoding.UTF8); // Step 2: Modify the content (example: replace text, append, etc.) string updatedContents = contents.Replace("old text", "new text"); // Or append: updatedContents = contents + "\nNew line added!"; // Step 3: Write the updated content back to the file // Use File.WriteAllText to overwrite, or File.AppendAllText to add to the end File.WriteAllText(path, updatedContents, Encoding.UTF8); Console.WriteLine("File updated successfully!"); } catch (IOException ex) { Console.WriteLine($"Error editing file: {ex.Message}"); } catch (UnauthorizedAccessException ex) { Console.WriteLine($"Permission denied: {ex.Message}"); }
Key Notes for Editing:
- Encoding: Always specify the encoding if your file uses something other than UTF-8 (e.g.,
Encoding.GetEncoding("GB2312")) to avoid garbled text. - Permissions: If your app is installed in a restricted folder (like
Program Files), you might get a permission error. Consider using the user's Documents folder instead:var docsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); var path = Path.Combine(docsPath, "YourAppName", "base.txt"); - File Locks: If another process is using the file,
File.ReadAllTextorFile.WriteAllTextwill throw an exception. For more robust handling, useFileStreamwith proper sharing options.
内容的提问来源于stack exchange,提问作者user18486531

