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

时间:2010-08-27 11:50:49

标签: c# .net windows wcf web-services

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

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

当我致电该服务时,它说“基础连接已关闭”。 你可以得到实施 http://cid-bafa39a62a57009c.office.live.com/self.aspx/.Public/MicaUpdaterService.zip  请帮帮我。

2 个答案:

答案 0 :(得分:5)

我在您的服务中找到了非常好的代码:

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

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

答案 1 :(得分:2)

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

相关问题