在WCF和Windows服务中下载大文件

我一直在创build一个新的服务来下载大文件到客户端。 我想在Windows服务中托pipe该服务。 在服务中,我写道:

public class FileTransferService : IFileTransferService { private string ConfigPath { get { return ConfigurationSettings.AppSettings["DownloadPath"]; } } private FileStream GetFileStream(string file) { string filePath = Path.Combine(this.ConfigPath, file); FileInfo fileInfo = new FileInfo(filePath); if (!fileInfo.Exists) throw new FileNotFoundException("File not found", file); return new FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read); } public RemoteFileInfo DownloadFile(DownloadRequest request) { FileStream stream = this.GetFileStream(request.FileName); RemoteFileInfo result = new RemoteFileInfo(); result.FileName = request.FileName; result.Length = stream.Length; result.FileByteStream = stream; return result; } } 

界面如下所示:

  [ServiceContract] public interface IFileTransferService { [OperationContract] RemoteFileInfo DownloadFile(DownloadRequest request); } [DataContract] public class DownloadRequest { [DataMember] public string FileName; } [DataContract] public class RemoteFileInfo : IDisposable { [DataMember] public string FileName; [DataMember] public long Length; [DataMember] public System.IO.Stream FileByteStream; public void Dispose() { if (FileByteStream != null) { FileByteStream.Close(); FileByteStream = null; } } } 

当我打电话给服务时,它说“底层连接已closures”。 你可以得到执行http://cid-bafa39a62a57009c.office.live.com/self.aspx/.Public/MicaUpdaterService.zip请帮助我。

我在您的服务中发现了非常好的代码:

 try { host.Open(); } catch {} 

这是最糟糕的反模式之一! 立即用正确的错误处理和记录替换这个代码。

我没有测试你的服务,只是通过查看配置和你的代码,我建议它永远不会工作,因为它不符合通过HTTP流式传输的要求。 当你想通过HTTP方法进行流式传输时,只能返回Stream类型的单个主体成员。 您的方法反而返回数据契约。 使用此版本:

 [ServiceContract] public interface IFileTransferService { [OperationContract] DownloadFileResponse DownloadFile(DownloadFileRequest request); } [MessageContract] public class DownloadFileRequest { [MessageBodyMember] public string FileName; } [MessageContract] public class DownloadFileResponse { [MessageHeader] public string FileName; [MessageHeader] public long Length; [MessageBodyMember] public System.IO.Stream FileByteStream; } 

不要关闭该服务的流。 关闭流是客户的责任。

看这篇文章。 这是你在找什么?