Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning a stream from File.OpenRead()

Tags:

c#

filestream

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?

like image 211
GrandMasterFlush Avatar asked Jan 05 '12 11:01

GrandMasterFlush


People also ask

What does OpenRead() do?

OpenRead(String) is an inbuilt File class method which is used to open an existing file for reading.

How do I return a streamed file?

To return a file stream, you can use a FileStreamResult. This lets you specify the stream, the MIME type, and some other options (like the file name). // the stream when the transfer is complete.

What are streams in C#?

What is C# Stream? In C# file operations, normally streams are used to read and write to files. A stream is an additional layer created between an application and a file. The stream is used to ensure smooth read and write operations to the file. Streams are normally used when reading data from large files.


1 Answers

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); 
like image 109
ken2k Avatar answered Sep 18 '22 17:09

ken2k