ErrLookup › Background articles › InvalidDataException: when .NET data is malformed, truncated, or in the wrong format
InvalidDataException: when .NET data is malformed, truncated, or in the wrong format
InvalidDataException is a System.IO exception that .NET libraries throw when the content of a file, stream, or payload does not match the format the parser expected. Developers meet it when JSON will not deserialize, an XML document has no root element, a binary header's magic bytes are wrong, a cached artifact is from an incompatible version, or a downloaded file changed mid-transfer. Unlike IOException (which blames the channel) or ArgumentException (which blames the caller), InvalidDataException blames the data itself, so the fix is almost always to repair, regenerate, or replace the offending input rather than to retry the call.
Distilled from 278 documented records across 26 repositories.
Background
InvalidDataException lives in the System.IO namespace and was introduced to signal that a data stream or file is in an unexpected, malformed, or unrecognizable format. It sits below the format-specific exceptions a library might also define. The distinguishing intent is the blame target: IOException faults the transport or disk, ArgumentException faults the calling code, but InvalidDataException faults the content of the bytes or text that were read. In every one of the documented records the throw site is hand-written library code that has just parsed input and found it inconsistent with an expected schema or invariant.,The layer that produces it is application-level parsing, deserialization, and format reading, not the runtime or the base class library itself. A library reads bytes or text from a file or network response, validates them against a structural contract, and throws when the contract is violated. The records show this gate operating on serialized text formats (JSON arrays containing null elements, XML documents with no root element, CSV rows shorter than their header), on binary headers (a VOC file whose description does not begin with 'Creative Voice File', a DependencyGraph whose magic signature does not match), on domain-specific configuration DSLs (OpenRA BooleanExpression tokens where a number is glued to an identifier), and on integrity metadata (a resumed download whose ETag changed between requests).,The family splits into several recognizable flavors. The largest group is structural validators that fire eagerly at load time: a file that parsed syntactically but is semantically empty or incomplete (an empty settings file, an XML snippet with no document element, a config whose root element is not the expected name). A second group is format-gate rejections, where a parser encounters a type tag, version byte, or terrain-type index it has no case for (.DS_Store record types, WAV format tags, tileset terrain bytes, DependencyGraph version numbers). A third group is integrity and restart guards, where an engine detects that a download or cached artifact can no longer be trusted (a changed ETag on resume, a bad Content-Range after a retry) and refuses to continue. A fourth, smaller group is defensive invariant guards on hardcoded constants (the OpenRA Huffman table and VOC frequency-divisor checks) that are effectively unreachable through normal input and surface instead as build or type-initialization defects.,From the caller's side the exception is synchronous, often fatal to the current operation, and carries a message that names the offending value and its source location. Because the blame is on content, the recovery direction is consistent across libraries: fix or replace the data, not retry it unchanged. The records repeatedly direct users to regenerate the file from a canonical source, restore a clean copy, delete a stale generated cache and rebuild, or convert the input to a standard supported format. Libraries that handle the exception robustly wrap their loaders in try/catch with a documented fallback (skip the malformed entry, fall back to a default theme, try the next format loader) rather than letting one bad record abort the entire operation.
Common causes
- Malformed or truncated serialized data.JSON, XML, or CSV input that opens but fails to map to the expected structure. Examples include a multiple-replace JSON file with trailing commas or unquoted keys, a settings file that is zero bytes or deserializes to null, an XML snippet with no root element, or a CSV data row with fewer columns than the header declared. The file was read successfully from disk but its content is structurally incomplete.
- Schema and structure violations in configuration.The input parses but violates a uniqueness or presence rule the loader enforces. Duplicate widget keys across chrome layout YAML files, a WinSW config whose root element is not <service>, an XML swatch <li> missing a required class attribute, or an OpenRA expression where a number sits directly adjacent to an identifier all trip a structural gate that the format alone would not catch.
- Wrong or unrecognized file format.A format-specific parser is handed data it was not built for. A WAV file whose audio-format tag matches no case in the sample-count switch, a .DS_Store with a record type outside the known set, a VOC file whose header description is not 'Creative Voice File', or a map whose tileset name is not registered in the active mod. The parser has no code path for the value it read.
- Cached or generated artifacts from an incompatible version.A binary cache file was written by a different version of the tool and is no longer readable. Unity's DependencyGraph throws when its magic signature or version byte does not match the current editor, and the prescribed remedy is to delete the Library/ folder and regenerate. The same shape appears wherever a serialized cache outlives the version that produced it.
- Corrupted binary or asset files.A binary asset is internally inconsistent in a way the loader detects defensively. An SHP-TD sprite whose frame reference chain forms a cycle longer than the frame count, a partially overwritten template file, or a byte-shifted .DS_Store stream all produce a throw that names the offending structure. The file exists and is the right format but its contents are damaged.
- Download integrity failures on resume.A paused download resumes but the server's response no longer matches the stored metadata. The Content-Range start byte differs from the requested offset, or the ETag and Last-Modified validators changed between the original and resumed requests, signaling that the remote artifact was replaced mid-transfer and a safe resume is impossible.
- Native interop and plugin process faults.A call across a native or process boundary fails and the managed wrapper re-throws as InvalidDataException. An ImageGlass native codec faults during decode and is wrapped with the codec ID and file path; a Flow Launcher JSON-RPC plugin writes to stderr before exiting and the buffered output is re-thrown to the host. The original failure is preserved as an inner exception or message text.
- Defensive invariant guards on constants.A minority of throws are dead-code guards on hardcoded values that normal input cannot reach. OpenRA's Huffman table construction checks an over-subscription invariant on constant arrays, and its VOC sample-rate formula guards against a divisor of 256 that a ReadUInt8 call can never produce. These surface as type-initialization or build defects, not as bad-data errors.
What usually fixes it
- Restore or regenerate the offending file from a canonical source. The most common remedy across the family is to obtain a clean copy: re-export from the tool's GUI, re-run the code generator, re-download the asset, or pull the file from a known-good revision rather than hand-editing damaged content.
- Validate input before you parse. Add pre-flight checks for file existence, non-zero length, correct extension, and magic bytes before handing the data to a deserializer or format reader, so failures point at the real cause instead of a null-root or null-deserialization throw deep inside the parser.
- Delete stale generated caches and rebuild. When the error names a version or signature mismatch in a generated artifact (Unity Library/, partial download .part files, DependencyGraph), removing the cached folder or file and letting the tool regenerate it from scratch is the documented fix.
- Standardize and pin the format, version, and environment. Use canonical formats (16-bit PCM WAV, immutable release URLs, the exact Unity version across team and CI), pin plugin runtime versions, and avoid mutable 'latest' links so the data the loader sees is always in a shape it was built for.
- Wrap format loaders in try/catch with a documented fallback. Libraries that degrade gracefully skip the malformed entry, fall back to a default theme or loader, or treat a parse failure as non-fatal when previewing, instead of letting one bad record abort the whole operation.
- Update or repair the tool that produced the malformed data. When the input comes from an external command whose output format has drifted (a Scoop export, a scraping step, a code generator), updating the tool or re-running the producing step resolves the structural mismatch at its source.
Go deeper
- Parsing and encoding errors: unexpected token, malformed input — why parsers reject input and how to find the real culprit.
Documented occurrences
- The updater download server returned an invalid partial content range.(Devolutions/UniGetUI)
- The input document does not contain a root(MaterialDesignInXAML/MaterialDesignInXamlToolkit)
- The updater download server returned partial content with a changed validator.(Devolutions/UniGetUI)
- Invalid frequency divisor 256 in voc file(OpenRA/OpenRA)
- over subscribed code set(OpenRA/OpenRA)
- Scoop export is in unkown or invalid format! Try updating Scoop and try again.\n\nContents:\n{result}(BCUninstaller/Bulk-Crap-Uninstaller)
- Number {Exts.ParseInt32Invariant(expression[start..i])} and variable merged at index {start}(OpenRA/OpenRA)
- Resource sprites specify different blend modes. Try using different ResourceRenderer traits for resource types that use different blend modes.(OpenRA/OpenRA)
- Format20/40 headers contain infinite loop(OpenRA/OpenRA)
- Unknown terrain type {terrainType} in {templateFilename}(OpenRA/OpenRA)
- The attribute 'class' was not found(MaterialDesignInXAML/MaterialDesignInXamlToolkit)
- IGE: Native codec '{CodecId}' threw during decode of '{filePath}'.(d2phap/ImageGlass)
- Widget has duplicate Key `{w.Key}` at {w.Location}(OpenRA/OpenRA)
- Failed to parse multiple-replace JSON at {path}: {ex.Message}(SubtitleEdit/subtitleedit)
- Invalid signature ({BitConverter.ToString(signatureHashSpan.ToArray())}) found (Expected: {BitConverter.ToString(Signature)}). DependencyGraph file is either corrupted or from a previous version of Unity. If you observe inexplicable runtime/compilation errors, please delete `Library/` folder and reopen the project.(Unity-Technologies/UnityCsReference)
- <JSON-RPC plugin process stderr>(Flow-Launcher/Flow.Launcher)
- JsonNode? pkg was null, when it shouldn't(Devolutions/UniGetUI)
- Voc header description not recognized(OpenRA/OpenRA)
- Unable to load '{themeFolderName}' theme pack. Please make sure '{themeConfigPath}' file is valid.(d2phap/ImageGlass)
- Settings file is empty or null: {path}(SubtitleEdit/subtitleedit)
…and 258 more across the corpus — use search.
Honest provenance: generated on 2026-08-13 from AI-assisted analysis of the linked records. See how records are made.