从多JSON文件读取ID至控件及OpenText方法重载错误解决
Hey there! Let's fix that "No overload for method 'OpenText' takes 2 arguments" error you're running into—it's a common mix-up with how File.OpenText() works.
What's causing the error?
File.OpenText() only accepts one argument: the full path to your JSON file. If you tried passing a second parameter (like an encoding type, e.g., Encoding.UTF8), that's exactly why you're getting the error. OpenText() defaults to UTF-8 encoding, so you don't need to specify it here. If you do need to use a different encoding, you'll need a different approach (more on that below).
First, let's fix the code
Let's start with the wrong code you might have written, then show the correct alternatives:
❌ Wrong (causes the error)
// Trying to pass encoding as a second argument to OpenText() using (var reader = File.OpenText("myfile.json", Encoding.UTF8)) { // ... your JSON parsing code }
✅ Correct Option 1: Use File.OpenText() as intended (UTF-8 only)
If your JSON files use UTF-8 encoding, stick to the single-parameter overload:
using (var reader = File.OpenText("myfile.json")) { string json = reader.ReadToEnd(); // Parse the JSON (using System.Text.Json or Newtonsoft.Json) var data = JsonSerializer.Deserialize<YourJsonModel>(json); // Add VersionId to ListBox listBox1.Items.Add(data.VersionId); }
✅ Correct Option 2: Specify encoding with StreamReader
If your JSON files use a non-UTF-8 encoding (like ASCII or UTF-16), use File.OpenRead() paired with StreamReader:
using (var fileStream = File.OpenRead("myfile.json")) using (var reader = new StreamReader(fileStream, Encoding.ASCII)) { string json = reader.ReadToEnd(); var data = JsonSerializer.Deserialize<YourJsonModel>(json); listBox1.Items.Add(data.VersionId); }
✅ Correct Option 3: Simplify with File.ReadAllText()
For even cleaner code, skip the stream readers entirely and use File.ReadAllText()—it lets you specify encoding directly if needed:
// UTF-8 (no encoding parameter needed) string json = File.ReadAllText("myfile.json"); // Or specify another encoding string json = File.ReadAllText("myfile.json", Encoding.Unicode); var data = JsonSerializer.Deserialize<YourJsonModel>(json); listBox1.Items.Add(data.VersionId);
Full Example: Load VersionIds from Multiple JSON Files into ListBox
Here's a complete, robust method that loops through all JSON files in a folder, parses their VersionId, and adds them to your ListBox (plus error handling):
// First, define a model to match your JSON structure public class JsonFileData { public string Id { get; set; } public string VersionId { get; set; } } private void LoadAllVersionIds() { listBox1.Items.Clear(); string jsonFolderPath = @"C:\Path\To\Your\Json\Files"; // Get all .json files in the folder string[] jsonFiles = Directory.GetFiles(jsonFolderPath, "*.json"); foreach (string filePath in jsonFiles) { try { string jsonContent = File.ReadAllText(filePath); JsonFileData data = JsonSerializer.Deserialize<JsonFileData>(jsonContent); // Only add if VersionId exists if (!string.IsNullOrEmpty(data?.VersionId)) { listBox1.Items.Add(data.VersionId); } } catch (Exception ex) { // Handle errors (e.g., invalid JSON, missing file) MessageBox.Show($"Failed to process {Path.GetFileName(filePath)}: {ex.Message}"); } } }
Bonus: Load a Single ID into TextBox
For reading an ID into your TextBox, use a similar approach:
private void LoadIdIntoTextBox(string filePath) { try { string jsonContent = File.ReadAllText(filePath); JsonFileData data = JsonSerializer.Deserialize<JsonFileData>(jsonContent); textBox1.Text = data?.Id ?? "No ID found in file"; } catch (Exception ex) { MessageBox.Show($"Error loading ID: {ex.Message}"); } }
Quick Notes
- Make sure you have the necessary using directives:
using System.IO; using System.Text; using System.Text.Json; // Or using Newtonsoft.Json; if you prefer that library - If you're using Newtonsoft.Json, replace
JsonSerializer.DeserializewithJsonConvert.DeserializeObject<JsonFileData>(jsonContent).
内容的提问来源于stack exchange,提问作者Mr_Ender57

