1

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);}     
} 
Community
  • 1
  • 1
GFXGunblade
  • 97
  • 3
  • 10

2 Answers2

6

If it says there's no data, then presumably there's no data.

My guess is that you've written to a MemoryStream and then passed that in as the input parmaeter without rewinding it first. (So its Position is the same as its Length - meaning there's nothing to read.) That's a common mistake.

Whatever's wrong, it isn't that method.

how can you tell if the source stream contains the correct information

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

Most likely you already read something from input stream and its Position is at the end of file. If source stream is seek-able just reset the position.

Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179