介绍
WCF(Windows Communication Foundation) - 消息处理:使用流数据传输文件,减少内存开销。
示例
1、服务
IStreamed.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; using System.IO; namespace WCF.ServiceLib.Message { /**//// /// 消息契约(定义与 SOAP 消息相对应的强类型类) /// [MessageContract] public class FileWrapper { /**//// /// 指定数据成员为 SOAP 消息头 /// [MessageHeader] public string FilePath; /**//// /// 指定将成员序列化为 SOAP 正文中的元素 /// [MessageBodyMember] public Stream FileData; } /**//// /// IStreamed接口 /// [ServiceContract] public interface IStreamed { /**//// /// 上传文件 /// /// /// 1、支持数据流传输的绑定有:BasicHttpBinding、NetTcpBinding 和 NetNamedPipeBinding /// 2、流数据类型必须是可序列化的 Stream 或 MemoryStream // /3、传递时消息体(Message Body)中不能包含其他数据,即参数中只能有一个System.ServiceModel.MessageBodyMember /**//// /// WCF.ServiceLib.Message.FileWrapper [OperationContract] void UploadFile(FileWrapper fileWrapper); } } |
Streamed.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; using System.IO; namespace WCF.ServiceLib.Message { /**//// /// IStreamed类 /// public class Streamed : IStreamed { /**//// /// 上传文件 /// /// WCF.ServiceLib.Message.FileWrapper public void UploadFile(FileWrapper fileWrapper) { var sourceStream = fileWrapper.FileData; var targetStream = new FileStream(fileWrapper.FilePath, FileMode.Create, FileAccess.Write, FileShare.None); var buffer = new byte[4096]; var count = 0; while ((count = sourceStream.Read(buffer, 0, buffer.Length)) > 0) { targetStream.Write(buffer, 0, count); } targetStream.Close(); sourceStream.Close(); } } } |