C# Get File Stream

Posted on  by admin
C# Get File Stream Rating: 4,1/5 1336 votes

I'm in the process of writing a WCF service that will allow an ASP.Net web site to retrieve files (based on this article). My problem is that when I return the stream, it's blank.

For simplicity, I've isolated the code into a simple winforms app to try and find what the problem is with returning a stream and this is the code:

The result of this code is that buf is 12,587 bytes long (the correct length of the file) but it just contains 0's.

The Word document opens without problems if I try it, am I missing something obvious?

GrandMasterFlushGrandMasterFlush

5 Answers

ken2kken2k

Ragini mms 2 movie online. Options: Watch online movie hollywood hindi dubbed.

  • Use data.Seek as suggested by ken2k
  • Use the somewhat simpler Position property:

  • Use the ToArray call in MemoryStream to make your life simpler to start with:

The third option would be my preferred approach.

Note that you should have a using statement to close the file stream automatically (and optionally for the MemoryStream), and I'd add a using directive for System.IO to make your code cleaner:

You might also want to create an extension method on Stream to do this for you in one place, e.g.

Note that this doesn't close the input stream.

Jon SkeetJon Skeet

You forgot to reset the position of the memory stream:

Update:

There is one more thing to note: It usually pays not to ignore the return values of methods. A more robust implementation should check how many bytes have been read after the call returns:

afrischkeafrischke

You need

And since your Test() method is imitating the client it ought to Close() or Dispose() the str Stream. And the memoryStream too, just out of principal.

Henk HoltermanHenk Holterman
ilivewithianilivewithian

Not the answer you're looking for? Browse other questions tagged c#filestream or ask your own question.