This article will share with you how to use WCF to transfer files.
Program Running Effect:
Receiving File:
Send File: connect to the WCF Service and select the file to be transferred.
File Transfer successful:
The default path of the file to be saved is c: \ Documents ents and Settings \ Administrator \ Desktop:
Code Analysis:
Here we will not describe the role of each code sentence one by one. Interested users can download the code, and there will be a download link later. Note the following:
Two days ago, someone asked Baidu if they could encapsulate the contract in WCF into a single class library. At that time, I felt that this was another option. I accidentally saw that the interface was separately divided and there was a good application, is to use the channel to implement client proxy.
Itransfer. CS
Code
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); // file transmission
}
[MessageContract]
Public class FileTransferMessage
{
[MessageHeader (MustUnderstand = true)]
Public string SavePath; // file storage path
[MessageHeader (MustUnderstand = true)]
Public string FileName; // file name
[MessageBodyMember (Order = 1)]
Public stream filedata; // File Transfer Time
}
}
Use a channel to create a client proxy:
Code
If (_ proxy = NULL)
{
Try
{
Nettcpbinding binding = new nettcpbinding ();
Binding. transfermode = transfermode. streamed;
Binding. SendTimeout = new TimeSpan (0, 30, 0 );
// Create a client proxy using the channel
_ 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;
}
In this way, you do not need to add service references or generate a proxy.
File Transfer functions are not difficult. The Code is as follows:
Code
Public void TransferFile (FileTransferMessage request)
{
String logInfo;
Program. Get_ILog (). Log (logInfo = string. Format ("start receiving file, name = {0}", request. FileName); // enter the Log
// File Information
String uploadFolder = AppValue. GetParam (). _ saveDir;
String savaPath = request. SavePath;
String fileName = request. FileName;
Stream sourceStream = request. FileData;
FileStream targetStream = null;
// Determine whether the object is readable
If (! Sourcestream. Canread)
{
Throw new exception ("the data stream is not readable! ");
}
If (savapath = NULL) savapath = @ "File Transfer \";
If (! Savapath. endswith ("\") savapath + = "\\";
If (! Uploadfolder. endswith ("\") uploadfolder + = "\\";
Uploadfolder = uploadfolder + savapath;
// Create a save folder
If (! Directory. Exists (uploadFolder ))
{
Directory. CreateDirectory (uploadFolder );
}
Int fileSize = 0;
String filePath = Path. Combine (uploadFolder, fileName); // Combine merges two paths
Try
{
// File stream transmission
Using (targetStream = new FileStream (filePath, FileMode. Create, FileAccess. Write, FileShare. None ))
{
// Define the File Buffer
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 ("received file completed name = {0}, filesize = {1 }",
Request. filename, filesize ));
}
If you are interested in other codes, download them and study them!
Source code download