1

I am working on developing an HTTP Server/Client and I can currently send small files over it such as .txt files and other easy to read files that do not require much memory. However when I want to send a larger file say a .exe or large .pdf I get memory errors. This are occurring from the fact that before I try to send or receive a file I have to specify the size of my byte[] buffer. Is there a way to get the size of the buffer while reading it from stream?

I want to do something like this:

//Create the stream. private Stream dataStream = response.GetResponseStream(); //read bytes from stream into buffer. byte[] byteArray = new byte[Convert.ToInt32(dataStream.Length)]; dataStream.read(byteArray,0,byteArray.Length); 

However when calling "dataStream.Length" it throws the error:

 ExceptionError: This stream does not support seek operations. 

Can someone offer some advice as to how I can get the length of my byte[] from the stream?

Thanks,

2 Answers 2

2

You can use CopyTo method of the stream.

MemoryStream m = new MemoryStream(); dataStream.CopyTo(m); byte[] byteArray = m.ToArray(); 

You can also write directly to file

var fs = File.Create("...."); dataStream.CopyTo(fs); 
Sign up to request clarification or add additional context in comments.

Comments

1

The network layer has no way of knowing how long the response stream is.

However, the server is supposed to tell you how long it is; look in the Content-Length response header.
If that header is missing or incorrect, you're out of luck; you'll need to keep reading until you run out of data.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.