Detect character sets using CharsetDetector
masterThe CharsetDetector class provides static methods to detect the character encoding of files, streams, or byte arrays. Detection results are returned as a DetectionResult object, which contains a list of possible matches (Details) and the most likely match (Detected).
Synchronous Detection
CharsetDetector.DetectFromFile(string path)or(FileInfo fileInfo): Detects encoding from a file.CharsetDetector.DetectFromStream(Stream stream): Detects encoding from a stream.CharsetDetector.DetectFromBytes(byte[] byteArray): Detects encoding from a byte array.
Asynchronous Detection
await CharsetDetector.DetectFromFileAsync(string path, CancellationToken cancellationToken)await CharsetDetector.DetectFromStreamAsync(Stream stream, CancellationToken cancellationToken)
Accessing Results
Once you have a DetectionResult, you can access the DetectionDetail for the best match via the .Detected property. From a DetectionDetail, you can retrieve:
EncodingName: The string alias of the encoding.Encoding: TheSystem.Text.Encodingobject (may benullif the encoding is not available in the current environment).Confidence: Afloatbetween 0 and 1 representing the detection certainty.Details: AnIList<DetectionDetail>containing all potential matches.
// Detect from File
DetectionResult result = CharsetDetector.DetectFromFile("path/to/file.txt");
// Get the best Detection
DetectionDetail resultDetected = result.Detected;
// Get the alias of the found encoding
string encodingName = resultDetected.EncodingName;
// Get the System.Text.Encoding of the found encoding (can be null if not available)
Encoding encoding = resultDetected.Encoding;
// Get the confidence of the found encoding (between 0 and 1)
float confidence = resultDetected.Confidence;
// Get all the details of the result
IList<DetectionDetail> allDetails = result.Details;