{"record":{"id":"ea9bfba22f3cf658","repo":"dotnet/machinelearning","slug":"stream-should-be-non-null-and-its-stream-canread-p","errorCode":null,"errorMessage":"Stream should be non-null and its stream.CanRead property should be true.","messagePattern":"Stream should be non-null and its stream\\.CanRead property should be true\\.","errorType":"exception","errorClass":"ArgumentException","httpStatus":null,"severity":"error","filePath":"src/Microsoft.ML.TorchSharp/Utils/FileUtils.cs","lineNumber":46,"sourceCode":"            typeof(double),\n        };\n\n        /// <summary>\n        /// Load a continuous segment of bytes from stream and parse them into a number array.\n        /// NOTE: this function is only for little-endian storage!\n        /// </summary>\n        /// <typeparam name=\"T\">should be a numeric type</typeparam>\n        /// <param name=\"stream\">the stream to read from its current position</param>\n        /// <param name=\"numElements\">expected number of parsed numbers</param>\n        /// <param name=\"tSize\">number of bytes occupied by the specified type</param>\n        /// <exception cref=\"NotSupportedException\">When the generic type T is not a valid numeric type.</exception>\n        /// <exception cref=\"ArgumentException\"/>\n        /// <exception cref=\"InvalidDataException\">When the contents in the stream don't match the need.</exception>\n        public static IEnumerable<T> LoadNumberArrayFromStream<T>(Stream stream, int numElements, int tSize)\n        {\n            if (stream == null || !stream.CanRead)\n            {\n                throw new ArgumentException($\"Stream should be non-null and its stream.CanRead property should be true.\");\n            }\n            if (!_validTypes.Contains(typeof(T)))\n            {\n                throw new NotSupportedException($\"Type {typeof(T)} not supported in data loading.\");\n            }\n\n            var numBytesConsumed = numElements * tSize;\n            var byteBuffer = new byte[numBytesConsumed];\n            var numBytesRead = stream.Read(byteBuffer, 0, numBytesConsumed);\n            if (numBytesConsumed != numBytesRead)\n            {\n                throw new InvalidDataException(\n                    $\"The number of bytes read from stream is less than expected. Please check the data files.\");\n            }\n\n            var targetBuffer = new T[numBytesConsumed / tSize];\n            Buffer.BlockCopy(byteBuffer, 0, targetBuffer, 0, numBytesConsumed);\n            return targetBuffer;","sourceCodeStart":28,"sourceCodeEnd":64,"githubUrl":"https://github.com/dotnet/machinelearning/blob/7b76e69cf964daeca3f1377af6bc5543284d56c6/src/Microsoft.ML.TorchSharp/Utils/FileUtils.cs#L28-L64","documentation":"LoadNumberArrayFromStream requires a readable Stream; it throws ArgumentException when the stream is null or stream.CanRead is false. This is an upfront guard so numeric model data (e.g., tensor weights) can actually be read from the stream.","triggerScenarios":"Passing a null Stream, a write-only stream (opened with FileAccess.Write), a closed/disposed stream whose CanRead returns false, or a stream wrapped for output (e.g., a File.OpenWrite stream).","commonSituations":"Opening a file with FileMode.Open/FileAccess.Write by mistake, reusing a stream already consumed and disposed, or passing null when an optional stream was never assigned.","solutions":["Open the file/stream with read access, e.g. `File.OpenRead(path)` or `new FileStream(path, FileMode.Open, FileAccess.Read)`.","Guard before calling: `if (stream is { CanRead: true }) ...` else re-open or fail fast.","Ensure the stream was not disposed/closed before the call; keep it open for the duration of the load.","Wrap the call in try-catch on ArgumentException to translate it into a user-facing data-loading error."],"exampleFix":"// before\nusing var stream = new FileStream(path, FileMode.Open, FileAccess.Write);\nFileUtils.LoadNumberArrayFromStream<float>(stream, n, 4); // throws\n\n// after\nusing var stream = File.OpenRead(path);\nFileUtils.LoadNumberArrayFromStream<float>(stream, n, 4); // OK","handlingStrategy":"validation","validationCode":"if (stream is null || !stream.CanRead)\n    throw new ArgumentException(\"A readable stream is required.\", nameof(stream));","typeGuard":"bool IsReadable(Stream? s) => s is { CanRead: true };","tryCatchPattern":"try { var data = FileUtils.LoadNumberArrayFromStream<float>(stream, n, 4); }\ncatch (ArgumentException ex) { log.LogError(ex, \"Stream must be non-null and readable\"); throw new ModelLoadException(...); }","preventionTips":["Open streams with FileAccess.Read / File.OpenRead.","Don't dispose streams before loading completes.","Null-check optional stream parameters at the call site."],"tags":["csharp","stream","argument-exception","io"],"backgroundTag":"invalid-argument-value","analyzedSha":"7b76e69cf964daeca3f1377af6bc5543284d56c6","analyzedAt":"2026-09-11T12:35:38.930Z","contentChangedAt":"2026-09-11T12:35:38.930Z","schemaVersion":2},"datasetVersion":"2026-09-14T05:17:10.506Z"}