分享WCF文件传输实现方法---WCFFileTransfer

 更新时间:2020年6月25日 11:26  点击:1483

前几天分享了分享了WCF聊天程序--WCFChat ,本文和大家一起分享利用WCF实现文件的传输。
程序运行效果:
接收文件端:

发送文件端:连接WCF服务,选择要传输的文件

文件传输成功:

我们会在保存文件的默认路径:C:\Documents and Settings\Administrator\桌面,下看到传输的文件:

代码分析:
这里就不一一的阐述每一句代码的作用了,感兴趣的朋友可以下载,文后会有下载链接。说下值得注意的地方:
前两天有人在百度知道中问能不能把WCF中的契约单独封装到一个类库中,当时感觉多此一举,无意中看到把接口单独分出去,有个很好的应用,就是利用通道实现客户端代理。
ITransfer.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Runtime.Serialization;
using System.Threading;
using System.IO;

namespace FileInterface
{
  [ServiceContract]
  public interface ITransfer
  {
    [OperationContract(Action = "UploadFile")]
    void TransferFile(FileTransferMessage request);//文件传输
  }


  [MessageContract]
  public class FileTransferMessage
  {
    [MessageHeader(MustUnderstand = true)]
    public string SavePath;//文件保存路径

    [MessageHeader(MustUnderstand = true)]
    public string FileName;//文件名称

    [MessageBodyMember(Order = 1)]
    public Stream FileData;//文件传输时间
  }
}

利用通道创建客户端代理:

if (_proxy == null)
      {
        try
        {
          NetTcpBinding binding = new NetTcpBinding();
          binding.TransferMode = TransferMode.Streamed;
          binding.SendTimeout = new TimeSpan(0, 30, 0);
          //利用通道创建客户端代理
          _proxy = ChannelFactory<ITransfer>.CreateChannel(binding, new EndpointAddress(CBSerURL.Text));
          IContextChannel obj = _proxy as IContextChannel;
          //string s = obj.SessionId;

        }
        catch (Exception ex)
        {
          MessageBox.Show(ex.Message);
          return;
        }

这样,既不用添加服务引用,也不需要生成代理。
文件传输的函数不是很难,代码如下:

public void TransferFile(FileTransferMessage request)
    {
      string logInfo;

      Program.Get_ILog().Log(logInfo = string.Format("开始接收文件,name={0}", request.FileName));//填写日志
      //文件信息
      string uploadFolder = AppValue.GetParam()._saveDir;
      string savaPath = request.SavePath;
      string fileName = request.FileName;
      Stream sourceStream = request.FileData;
      FileStream targetStream = null;
      //判断文件是否可读
      if (!sourceStream.CanRead)
      {
        throw new Exception("数据流不可读!");
      }
      if (savaPath == null) savaPath = @"文件传输\";
      if (!savaPath.EndsWith("\\")) savaPath += "\\";
      if (!uploadFolder.EndsWith("\\")) uploadFolder += "\\";

      uploadFolder = uploadFolder + savaPath;
      //创建保存文件夹
      if (!Directory.Exists(uploadFolder))
      {
        Directory.CreateDirectory(uploadFolder);
      }

      int fileSize = 0;
      string filePath = Path.Combine(uploadFolder, fileName);//Combine合并两个路径
      try
      {
        //文件流传输
        using (targetStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
        {
          //定义文件缓冲区
          const int bufferLen = 4096;
          byte[] buffer = new byte[bufferLen];
          int count = 0;

          while ((count = sourceStream.Read(buffer, 0, bufferLen)) > 0)
          {
            targetStream.Write(buffer, 0, count);
            fileSize += count;
          }
          targetStream.Close();
          sourceStream.Close();
        }
      }
      catch (Exception ex)
      {
        Program.Get_ILog().Log(logInfo + ex.Message);
      }

      Program.Get_ILog().Log(string.Format("接收文件完毕 name={0},filesize={1}",
       request.FileName, fileSize));
    }

其他的代码感兴趣的朋友下载来研究吧!


源代码:WCFFileTransfer.rar

[!--infotagslink--]

相关文章