Returning a stream from File.OpenRead()

GrandMasterFlush picture GrandMasterFlush · Jan 5, 2012 · Viewed 167.2k times · Source

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:

    private Stream TestStream()
    {
        Stream fs = File.OpenRead(@"c:\testdocument.docx");
        return fs;
    }

    // This method converts the filestream into a byte array so that when it is 
    // used in my ASP.Net project the file can be sent using response.Write
    private void Test()
    {            
        System.IO.MemoryStream data = new System.IO.MemoryStream();
        System.IO.Stream str = TestStream();

        str.CopyTo(data);
        byte[] buf = new byte[data.Length];
        data.Read(buf, 0, buf.Length);                       
    }

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?

Answer

ken2k picture ken2k · Jan 5, 2012

You forgot to seek:

str.CopyTo(data);
data.Seek(0, SeekOrigin.Begin); // <-- missing line
byte[] buf = new byte[data.Length];
data.Read(buf, 0, buf.Length);