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

2019-12-26 14:08:47于海丽

这样,既不用添加服务引用,也不需要生成代理。

文件传输的函数不是很难,代码如下:

 

 
  1. public void TransferFile(FileTransferMessage request)  { 
  2. string logInfo;   
  3. Program.Get_ILog().Log(logInfo = string.Format("开始接收文件,name={0}", request.FileName));//填写日志  //文件信息 
  4. string uploadFolder = AppValue.GetParam()._saveDir;  string savaPath = request.SavePath; 
  5. string fileName = request.FileName;  Stream sourceStream = request.FileData; 
  6. FileStream targetStream = null;  //判断文件是否可读 
  7. if (!sourceStream.CanRead)  { 
  8. throw new Exception("数据流不可读!");  } 
  9. if (savaPath == null) savaPath = @"文件传输";  if (!savaPath.EndsWith("")) savaPath += ""; 
  10. if (!uploadFolder.EndsWith("")) uploadFolder += "";   
  11. uploadFolder = uploadFolder + savaPath;  //创建保存文件夹 
  12. if (!Directory.Exists(uploadFolder))  { 
  13. Directory.CreateDirectory(uploadFolder);  } 
  14.   int fileSize = 0; 
  15. string filePath = Path.Combine(uploadFolder, fileName);//Combine合并两个路径  try 
  16. {  //文件流传输 
  17. using (targetStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))  { 
  18. //定义文件缓冲区  const int bufferLen = 4096; 
  19. byte[] buffer = new byte[bufferLen];  int count = 0; 
  20.   while ((count = sourceStream.Read(buffer, 0, bufferLen)) > 0) 
  21. {  targetStream.Write(buffer, 0, count); 
  22. fileSize += count;  } 
  23. targetStream.Close();  sourceStream.Close(); 
  24. }  } 
  25. catch (Exception ex)  { 
  26. Program.Get_ILog().Log(logInfo + ex.Message);  }