I’ve been trying to do a basic copy from a source stream to a destination stream. I’ve been using many questions previously asked as good examples for implementation such as How do I save a stream to a file in C#?. However, when the code below executes, it exits on first run stating there is no data to copy. My question is how can you tell if the source stream contains the correct information to stream from one file to another?
The code looks like this from the link above:
public static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[8192];
int len;
while ( (len = input.Read(buffer, 0, buffer.Length)) > 0)
{output.Write(buffer, 0, len);}
}
If it says there’s no data, then presumably there’s no data.
My guess is that you’ve written to a
MemoryStreamand then passed that in as theinputparmaeter without rewinding it first. (So itsPositionis the same as itsLength– meaning there’s nothing to read.) That’s a common mistake.Whatever’s wrong, it isn’t that method.
In code? You can’t – because the stream has no way of knowing what you mean by “the correct information”. You could write checks to expect that the stream isn’t empty, etc… but of course that will fail if you’re ever trying to copy an empty file. Without any more information, any sequence of bytes could be correct.