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?
OpenRead(String) is an inbuilt File class method which is used to open an existing file for reading.
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 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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With