如何将CSV读取到C#类并构建PUT请求提交数据
Hey Laura, let's get your code working properly! You're almost there—we just need to add the CSV parsing logic and wire up the JSON request body. Let's break this down step by step:
1. Parsing the CSV Rows
First, we need to split each line into id and name. A few quick considerations:
- If your CSV has a header row (like
id,name), we should skip it to avoid treating column names as data. - For simple CSVs (no commas inside the
namevalues), a basicSplit(',')works, but if names might contain commas, you’ll want a dedicated CSV library like CsvHelper for reliability (we’ll stick to vanilla .NET for this example though).
Here’s how to update your loop to handle row splitting:
try { var csv = new List<Department>(); var lines = System.IO.File.ReadAllLines(@"C:\file.csv"); // Skip header row if your CSV includes one for (int i = 1; i < lines.Length; i++) { string line = lines[i]; string[] parts = line.Split(','); // Guard against malformed lines if (parts.Length >= 2) { string id = parts[0].Trim(); // Trim extra whitespace just in case string name = parts[1].Trim(); csv.Add(new Department { id = id, name = name }); // Now we can build the URL and send the PUT request string url = $"https://www.test.com/department/{id}"; // We'll handle the request logic next... } else { Console.WriteLine($"Skipping invalid line: {line}"); } } } catch (Exception ex) { Console.WriteLine($"Error reading CSV: {ex.Message}"); }
2. Building the JSON Body & Sending the PUT Request
Instead of using HttpWebRequest (which is a bit outdated), let’s use HttpClient—it’s simpler, more efficient, and designed for repeated requests. We’ll also use .NET’s built-in System.Text.Json to serialize your Department object to JSON.
Here’s the full updated code with request handling:
// Reuse a single HttpClient instance (prevents socket exhaustion!) private static readonly HttpClient _httpClient = new HttpClient(); static async Task Main(string[] args) { try { var csv = new List<Department>(); var lines = System.IO.File.ReadAllLines(@"C:\file.csv"); // Set authorization header once for all requests _httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "77ba42a2d0511e109068bcb9857d035da27a4eae"); // Skip header row for (int i = 1; i < lines.Length; i++) { string line = lines[i]; string[] parts = line.Split(','); if (parts.Length >= 2) { string id = parts[0].Trim(); string name = parts[1].Trim(); var department = new Department { id = id, name = name }; csv.Add(department); // Build target URL string url = $"https://www.test.com/department/{id}"; // Serialize department to JSON request body string jsonBody = System.Text.Json.JsonSerializer.Serialize(department); var content = new StringContent(jsonBody, System.Text.Encoding.UTF8, "application/json"); // Send PUT request asynchronously HttpResponseMessage response = await _httpClient.PutAsync(url, content); // Handle response status if (response.IsSuccessStatusCode) { Console.WriteLine($"Successfully updated department {id}"); } else { string errorDetails = await response.Content.ReadAsStringAsync(); Console.WriteLine($"Failed to update {id}. Status: {response.StatusCode}. Error: {errorDetails}"); } } else { Console.WriteLine($"Skipping invalid line: {line}"); } } } catch (Exception ex) { Console.WriteLine($"Unexpected error: {ex.Message}"); } } public class Department { public string id { get; set; } public string name { get; set; } }
Quick Tips:
- Reuse
HttpClient: Creating a new instance per request can cause socket exhaustion, so a static instance is better. - Async/Await: Using async operations keeps your code non-blocking, which is ideal for I/O tasks like HTTP requests.
- Error Handling: We added checks for malformed CSV lines and HTTP failures to help you debug issues.
- Complex CSVs: If your CSV has quoted fields or commas inside names, grab the CsvHelper NuGet package—it handles edge cases way better than a simple
Split(',').
内容的提问来源于stack exchange,提问作者Laura Bejjani
相关产品推荐
相关产品推荐

