Unable to read outside the stream

I made a quick method to write a file from a stream, but it has not yet been executed. I get this exception and I cannot find the reason:

Unable to read beyond the end of the stream 

Is there anyone who could debug it for me?

 public static bool WriteFileFromStream(Stream stream, string toFile) { FileStream fileToSave = new FileStream(toFile, FileMode.Create); BinaryWriter binaryWriter = new BinaryWriter(fileToSave); using (BinaryReader binaryReader = new BinaryReader(stream)) { int pos = 0; int length = (int)stream.Length; while (pos < length) { int readInteger = binaryReader.ReadInt32(); binaryWriter.Write(readInteger); pos += sizeof(int); } } return true; } 

Thanks a lot!

+6
source share
5 answers

Not quite the answer to your question, but this method can be much simpler:

 public static void WriteFileFromStream(Stream stream, string toFile) { // dont forget the using for releasing the file handle after the copy using (FileStream fileToSave = new FileStream(toFile, FileMode.Create)) { stream.CopyTo(fileToSave); } } 

Please note that I also deleted the return value, since it is almost useless since there is only 1 return statement in your code

In addition, you perform length checking on a stream, but many threads do not support length checking.

As for your problem, first check if the thread has completed. If not, you read 4 bytes. Here is the problem. Suppose you have an input stream of 6 bytes. First you check if the stream is at the end. The answer is no, since there are 6 bytes left. You read 4 bytes and check again. Of course, the answer is still missing, as 2 bytes remain. Now you read 4 more bytes, but this fails, since there are only 2 bytes. (readInt32 reads the next 4 bytes).

+5
source

I assume that the input stream has only ints (Int32). You need to test the PeekChar() method,

 while (binaryReader.PeekChar() != -1) { int readInteger = binaryReader.ReadInt32(); binaryWriter.Write(readInteger); } 
+2
source

You execute while (pos <length), and length is the actual length of the stream in bytes. This way you efficiently count the bytes in the stream and then try to read that many numbers are int (which is wrong). You can take the length of stream.Length / 4, since Int32 has 4 bytes.

+1
source

to try

 int length = (int)binaryReader.BaseStream.Length; 
0
source

After reading the stream with the binary reader, the position of the stream at the end, you should set the position to zero "stream.position = 0;"

0
source

Source: https://habr.com/ru/post/899576/


All Articles