Free tools Windows power users keep installed
One-click scans. No signup required.
Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
The right C# extraction technique depends on the input format, how stable its schema is, and whether you can process it sequentially. Use System.Text.Json typed deserialization for predictable JSON, JsonDocument for variable JSON, HttpClient for web APIs, XmlReader for forward-only XML, and a format-specific library such as ExcelDataReader or CsvHelper for tabular files.
Choose an extraction strategy first
Identify three properties before writing code:
- Format: JSON, XML, CSV and Excel have different parsing rules.
- Schema: a known, stable shape favors typed objects; an unknown or changing shape favors DOM inspection.
- Processing model: in-memory DOM APIs support random access, while readers process a document sequentially and use less retained state.
| Input | Recommended starting point | Important trade-off |
|---|---|---|
| Known JSON contract | JsonSerializer.Deserialize<T> |
Clear types and validation, but the model must match the payload. |
| Variable JSON | JsonDocument |
Flexible property selection, with manual type and presence checks. |
| HTTP JSON API | HttpClient plus System.Net.Http.Json |
Convenient retrieval, but status codes and non-JSON responses still need handling. |
| Large or sequential XML | XmlReader |
Forward-only traversal; no random access without storing data yourself. |
| CSV | ExcelDataReader or CsvHelper | Fields may arrive as strings, so your code must parse and validate types. |
| Excel workbook | ExcelDataReader | Choose row/sheet iteration or its DataSet convenience path. |
Extract values from JSON with a known structure
When the payload has a documented shape, create C# types and deserialize into them. Microsoft describes System.Text.Json as providing high-performance, low-allocating, standards-compliant JSON processing with built-in UTF-8 support. The following complete program reads a file, extracts selected values and reports malformed input.
using System.Text.Json;
public sealed record Customer(int Id, string Name, string? Email);
const string path = "customer.json";
try
{
await using FileStream stream = File.OpenRead(path);
Customer? customer = await JsonSerializer.DeserializeAsync<Customer>(stream);
if (customer is null)
throw new InvalidDataException("The JSON value was null.");
Console.WriteLine($"{customer.Id}: {customer.Name} ({customer.Email ?? "no email"})");
}
catch (JsonException ex)
{
Console.Error.WriteLine($"Invalid JSON or incompatible data: {ex.Message}");
}
catch (IOException ex)
{
Console.Error.WriteLine($"Could not read the file: {ex.Message}");
}
Understand the defaults
Property-name matching is case-sensitive by default. Properties present in JSON but not represented by your C# type are ignored by default. Missing values can still be a problem when your model or newer required-member behavior expects them. Make the contract explicit when input varies:
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
AllowTrailingCommas = true,
ReadCommentHandling = JsonCommentHandling.Skip
};
Customer? customer = JsonSerializer.Deserialize<Customer>(json, options);
Use converters when a source encodes dates, numbers or other values in a nonstandard way. Do not enable permissive settings casually for untrusted data: they can hide producer errors that should be fixed or rejected.
#1 Best Overall
Extract selected values from variable JSON
If you do not know the complete shape, parse a DOM and inspect only the values you need. This avoids inventing a class hierarchy for every possible response.
using System.Text.Json;
using JsonDocument document = await JsonDocument.ParseAsync(File.OpenRead("payload.json"));
JsonElement root = document.RootElement;
if (root.TryGetProperty("customer", out JsonElement customer) &&
customer.TryGetProperty("id", out JsonElement id) &&
id.TryGetInt32(out int customerId))
{
string name = customer.TryGetProperty("name", out JsonElement nameElement)
? nameElement.GetString() ?? ""
: "";
Console.WriteLine($"{customerId}: {name}");
}
else
{
Console.Error.WriteLine("customer.id is missing or is not an integer.");
}
JsonDocument keeps a structured representation in memory, so it supports random access but is not a streaming substitute for very large documents. Dispose it after use. For arrays, enumerate with EnumerateArray(); for unknown objects, enumerate properties with EnumerateObject(). Prefer TryGetProperty and TryGetInt32 when fields are optional or supplied by external systems.
Extract JSON from an HTTP API
HttpClient and System.Net.Http.Json provide a compact path from an endpoint to a typed object. Check the contract, status code, cancellation and content type instead of assuming every successful request contains valid JSON.
The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Rank #2
using System.Net.Http.Json;
using System.Text.Json;
using var client = new HttpClient { BaseAddress = new Uri("https://api.example.com/") };
using var cancellation = new CancellationTokenSource(TimeSpan.FromSeconds(30));
try
{
using HttpResponseMessage response = await client.GetAsync("customers/42", cancellation.Token);
response.EnsureSuccessStatusCode();
Customer? customer = await response.Content.ReadFromJsonAsync<Customer>(
cancellationToken: cancellation.Token);
if (customer is null)
throw new JsonException("The endpoint returned JSON null.");
Console.WriteLine(customer.Name);
}
catch (HttpRequestException ex)
{
Console.Error.WriteLine($"Network or HTTP failure: {ex.Message}");
}
catch (TaskCanceledException)
{
Console.Error.WriteLine("The request timed out or was cancelled.");
}
catch (JsonException ex)
{
Console.Error.WriteLine($"Response was not the expected JSON: {ex.Message}");
}
For a one-line retrieval and deserialization operation, GetFromJsonAsync<T> can fit, but you still need exception handling and an endpoint contract. A 200 response may contain HTML, an error envelope or an empty body, especially when a proxy, login page or rate limiter intervenes.
Read XML sequentially with XmlReader
XmlReader is a forward-only, noncached reader. Each call to Read advances one node, making it suitable for selective extraction from large or sequential XML input.
using System.Xml;
var settings = new XmlReaderSettings { IgnoreWhitespace = true };
using XmlReader reader = XmlReader.Create("orders.xml", settings);
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element && reader.Name == "order")
{
string? id = reader.GetAttribute("id");
Console.WriteLine($"Order {id}");
}
if (reader.NodeType == XmlNodeType.Element && reader.Name == "total")
{
string value = reader.ReadElementContentAsString();
if (decimal.TryParse(value, out decimal total))
Console.WriteLine(total);
}
}
Because traversal is forward-only, you cannot jump back to an earlier node. Store values you will need later. Malformed XML can raise XmlException; catch it at the boundary where you report or reject the file. For untrusted XML, use appropriate secure reader settings and avoid resolving external entities.
Extract CSV and Excel data
ExcelDataReader
ExcelDataReader documents navigation through worksheets and rows, CSV parsing, and a DataSet convenience path. Its CSV reader yields fields as strings, so your application must validate and convert numbers, dates and other types.
using System.Globalization;
using ExcelDataReader;
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
using var stream = File.OpenRead("sales.csv");
using IExcelDataReader reader = ExcelReaderFactory.CreateCsvReader(stream);
while (reader.Read())
{
string sku = reader.GetString(0) ?? "";
string rawAmount = reader.GetString(1) ?? "";
if (!decimal.TryParse(rawAmount, NumberStyles.Number,
CultureInfo.InvariantCulture, out decimal amount))
{
Console.Error.WriteLine($"Invalid amount for {sku}: {rawAmount}");
continue;
}
Console.WriteLine($"{sku}: {amount}");
}
For workbooks, inspect reader.Name, call NextResult() to move between sheets, and iterate rows with Read(). The DataSet path is convenient when the workbook fits comfortably in memory; row-by-row navigation gives you more control over what you retain.
CsvHelper
CsvHelper is another documented .NET library for reading and writing CSV. It is useful when you want header mapping, strongly typed records and configurable delimiter or culture handling. Regardless of library, define what happens for blank fields, duplicate headers, quoted delimiters and invalid rows.
Rank #4
Validation, memory and reliability
- Validate required fields immediately after parsing; do not let default values silently become business data.
- Use invariant culture or the producer’s documented culture for machine-generated numbers and dates.
- For large JSON, avoid loading the entire file into a string when a stream-based API is sufficient.
- For XML, keep extraction state small because the reader does not provide random access.
- For HTTP, reuse
HttpClient, set cancellation or timeouts, and distinguish transport failures from non-success status codes and schema failures. - Log enough context to repair a bad record without logging secrets, authorization headers or personal data.
Troubleshooting common failures
| Symptom | Likely cause | Fix |
|---|---|---|
JsonException |
Malformed JSON, wrong property type or unexpected format. | Capture the failing payload safely, inspect the contract, then add a converter or correct the producer. |
| Properties are null | Case-sensitive names, missing fields or mismatched nesting. | Check the exact JSON path; use case-insensitive options only when appropriate. |
| HTTP call returns JSON parse errors | The server returned HTML, an error envelope or an empty body. | Inspect status and content type before deserializing; retain a bounded error body for diagnostics. |
XmlException |
Malformed XML or invalid character data. | Validate the source and report line/position information from the exception. |
| CSV numbers fail to parse | Fields are strings and culture, separators or decimal symbols differ. | Choose the correct culture, validate each field and handle bad rows explicitly. |
| Missing Excel rows or values | Wrong sheet, header offset or assumptions about empty cells. | Print sheet names and column indexes while diagnosing, then encode the workbook layout deliberately. |
Or skip the browser setup
If your extraction starts with a web page rather than an API, ScreenshotNeo can return a clean screenshot or PDF through one GET request. It accepts cookie or consent banners as a visitor and removes more than 60 known consent platforms, newsletter popups and chat widgets before capture; each cleanup step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server exposes take_screenshot, get_page_info and capture_pdf to Claude, Cursor and other MCP clients.
Use the ScreenshotNeo API documentation for options such as full-page lazy-image loading, CSS-selector element capture, custom JavaScript and CSS, waits, request blocking, cookies, headers, user agents, device presets, retina scale, PDF ranges, signed links, asynchronous webhooks, bulk capture and caching.
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Scan for outdated or missing drivers - takes under a minuteDriver Scan →curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
There is a free allowance of 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 shots; every feature is included on every plan. Create a free ScreenshotNeo account to try it.
FAQ
Should I use a class or a JSON DOM?
Use a class when the schema is known and stable. Use JsonDocument when you need a few fields from variable payloads.
Best Value
Can XmlReader move backward?
No. It is forward-only; retain any values required after the reader passes them.
Does a CSV reader know whether a field is a date or number?
Not necessarily. ExcelDataReader documents CSV fields as strings, so your code must interpret and validate them.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Repair Windows errors before they cause bigger problems3Scan for outdated or missing drivers - takes under a minuteFrequently Asked Questions
What is the simplest way to extract JSON in C#?
Deserialize into a matching C# type with System.Text.Json when the JSON schema is known; use JsonDocument for selective access to an unknown shape.
How should I handle an API that sometimes returns HTML?
Check the HTTP status and content type before deserialization, then report or inspect the bounded response body when it is not the expected JSON.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

