我正在编写一个 WCF 服务,该服务将允许 ASP.Net 网站检索文件(基于本文 http://msdn.microsoft.com/en-us/library/ms789010.aspx#Y912)。我的问题是,当我返回流时,它是空白的。
为简单起见,我将代码隔离到一个简单的 winforms 应用程序中,以尝试找出返回流的问题所在,代码如下:
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。
如果我尝试打开 Word 文档,则不会出现任何问题,我是否遗漏了一些明显的内容?
你忘了Seek
:
str.CopyTo(data);
data.Seek(0, SeekOrigin.Begin); // <-- missing line
byte[] buf = new byte[data.Length];
data.Read(buf, 0, buf.Length);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)