{"record":{"id":"52d7e480527e6c84","repo":"HandyOrg/HandyControl","slug":"wrote-an-incorrect-number-of-bytes","errorCode":null,"errorMessage":"Wrote an incorrect number of bytes","messagePattern":"Wrote an incorrect number of bytes","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"src/Shared/HandyControl_Shared/Data/Gif/GPStream.cs","lineNumber":92,"sourceCode":"    ]\n    public virtual long CopyTo(InteropValues.IStream pstm, long cb, long[] pcbRead)\n    {\n\n        const int bufsize = 4096;\n        var buffer = Marshal.AllocHGlobal(bufsize);\n        if (buffer == IntPtr.Zero) throw new OutOfMemoryException();\n        long written = 0;\n        try\n        {\n            while (written < cb)\n            {\n                var toRead = bufsize;\n                if (written + toRead > cb) toRead = (int) (cb - written);\n                var read = Read(buffer, toRead);\n                if (read == 0) break;\n                if (pstm.Write(buffer, read) != read)\n                {\n                    throw EFail(\"Wrote an incorrect number of bytes\");\n                }\n                written += read;\n            }\n        }\n        finally\n        {\n            Marshal.FreeHGlobal(buffer);\n        }\n        if (pcbRead != null && pcbRead.Length > 0)\n        {\n            pcbRead[0] = written;\n        }\n\n        return written;\n    }\n\n    public virtual Stream GetDataStream()\n    {","sourceCodeStart":74,"sourceCodeEnd":110,"githubUrl":"https://github.com/HandyOrg/HandyControl/blob/2c0875ebd67326e0c67282967e3e809c69282fee/src/Shared/HandyControl_Shared/Data/Gif/GPStream.cs#L74-L110","documentation":"HandyControl's GPStream (a COM IStream wrapper used for GIF decoding) throws EFail with \"Wrote an incorrect number of bytes\" during CopyTo when the wrapped pstm.Write call returns a byte count different from the number of bytes Read returned. This is an internal invariant violation indicating the underlying IStream implementation misbehaved (short write or reported count mismatch).","triggerScenarios":"CopyTo copies cb bytes in bufsize chunks; if Read(buffer, toRead) returns read > 0 but pstm.Write(buffer, read) returns any value != read, the exception is thrown on the very next loop iteration check.","commonSituations":"Decoding a GIF via a stream backed by a COM/interop IStream (e.g. from clipboard, OLE storage, or a native component) whose Write implementation is buggy or partially fails mid-copy; disk-full or stream closed underneath during copy.","solutions":["Check the health of the underlying stream source (disk space, whether the COM stream was disposed/closed by another owner).","Re-load the GIF from a fresh stream (e.g. new FileStream/MemoryStream) rather than reusing a suspect COM stream.","If the stream comes from interop, verify the IStream implementation correctly returns the number of bytes written from Write.","Wrap copy/decode calls in try-catch for COMException/IOException and fall back to an alternative decoder path."],"exampleFix":null,"handlingStrategy":"try-catch","validationCode":"// Before decoding, confirm the stream is readable and has data:\nif (stream == null || !stream.CanRead || stream.Length == 0)\n    throw new InvalidOperationException(\"GIF source stream is unreadable or empty\");","typeGuard":"static bool IsUsableStream(System.IO.Stream s) =>\n    s != null && s.CanRead && (s.CanSeek ? s.Length > 0 : true);","tryCatchPattern":"try\n{\n    // decode GIF via GPStream-backed object\n}\ncatch (System.Runtime.InteropServices.COMException ex)\n    when (ex.Message.Contains(\"Wrote an incorrect number of bytes\"))\n{\n    // re-acquire a fresh stream and retry once, else fall back to alternate loader\n}","preventionTips":["Do not share one COM IStream across components; give each decoder its own stream.","Keep the native stream alive until all copy/decode work completes.","Check disk space and stream disposal order before GIF decode.","Wrap interop decoding in a retry with a freshly opened stream."],"tags":["csharp","com-interop","istream","gif","stream"],"backgroundTag":"internal-invariant-violation","analyzedSha":"2c0875ebd67326e0c67282967e3e809c69282fee","analyzedAt":"2026-09-14T14:45:29.754Z","contentChangedAt":"2026-09-14T14:45:29.754Z","schemaVersion":2},"datasetVersion":"2026-09-16T09:17:16.951Z"}