分享WCF文件傳輸完成辦法---WCFFileTransfer。本站提示廣大學習愛好者:(分享WCF文件傳輸完成辦法---WCFFileTransfer)文章只能為提供參考,不一定能成為您想要的結果。以下是分享WCF文件傳輸完成辦法---WCFFileTransfer正文
頭幾天分享了分享了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