从File.OpenRead返回一个流() [英] Returning a stream from File.OpenRead()

查看:939
本文介绍了从File.OpenRead返回一个流()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在写一个WCF服务,将允许一个ASP.Net网站检索文件(基于的这篇文章)。我的问题是,当我返回流,它是空白的。

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.

为了简单起见,我已经分离出的代码放到一个简单的WinForms应用程序,试图找到问题是什么与返回的流,这是代码:

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);                       
    }



这段代码的结果是 BUF 为12,587字节(文件的正确长度),但只包含0。

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.

在Word文档没有问题打开,如果我尝试它,我?我失去了一些东西明显

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

推荐答案

您忘了求:

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

这篇关于从File.OpenRead返回一个流()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆