版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yuliqi0429/article/details/51086946
1.首先利用vs创建WCF服务程序。
2.添加接口文件和服务文件
IServiceFile.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace UploadFile
{
// 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码和配置文件中的接口名“IServiceFile”。
[ServiceContract]
public interface IServiceFile
{
/// <summary>
/// 上传操作
/// </summary>
/// <param name="fileInfo"></param>
/// <returns></returns>
[OperationContract]
CustomFileInfo UpLoadFileInfo(CustomFileInfo fileInfo);
/// <summary>
/// 获取文件操作
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
[OperationContract]
CustomFileInfo GetFileInfo(string fileName, string uploadPath);
/// <summary>
/// 删除文件操作
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
[OperationContract]
bool DeleteFile(string filedPath);
}
/// <summary>
/// 自定义文件属性类
/// </summary>
[DataContract]
public class CustomFileInfo
{
/// <summary>
/// 文件名称
/// </summary>
[DataMember]
public string Name { get; set; }
/// <summary>
/// 文件大小
/// </summary>
[DataMember]
public long Length { get; set; }
/// <summary>
/// 文件偏移量
/// </summary>
[DataMember]
public long OffSet { get; set; }
/// <summary>
/// 发送的字节
/// </summary>
[DataMember]
public byte[] SendByte { get; set; }
/// <summary>
/// 上传到服务器的物理位置
/// </summary>
[DataMember]
public string UploadPath { get; set; }
}
}
ServiceFile.svc
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace UploadFile
{
// 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码、svc 和配置文件中的类名“ServiceFile”。
// 注意: 为了启动 WCF 测试客户端以测试此服务,请在解决方案资源管理器中选择 ServiceFile.svc 或 ServiceFile.svc.cs,然后开始调试。
public class ServiceFile : IServiceFile
{
public CustomFileInfo UpLoadFileInfo(CustomFileInfo fileInfo)
{
// 获取服务器文件上传路径
string fileUpLoadPath = "D:\\UploadFile\\";
if (fileInfo.UploadPath != null && fileInfo.UploadPath != "")
{
fileUpLoadPath = fileInfo.UploadPath;
}
if (!Directory.Exists(fileUpLoadPath))
{
Directory.CreateDirectory(fileUpLoadPath);
}
if (!fileUpLoadPath.EndsWith("\\"))
{
fileUpLoadPath = fileUpLoadPath + "\\";
}
// 如需指定新的文件夹,需要进行创建操作。
Console.WriteLine("1");
// 创建FileStream对象
FileStream fs = new FileStream(fileUpLoadPath + fileInfo.Name, FileMode.OpenOrCreate);
Console.WriteLine("2");
long offSet = fileInfo.OffSet;
// 使用提供的流创建BinaryWriter对象
var binaryWriter = new BinaryWriter(fs, Encoding.UTF8);
binaryWriter.Seek((int)offSet, SeekOrigin.Begin);
binaryWriter.Write(fileInfo.SendByte);
fileInfo.OffSet = fs.Length;
fileInfo.SendByte = null;
binaryWriter.Close();
fs.Close();
Console.WriteLine("2");
return fileInfo;
}
public CustomFileInfo GetFileInfo(string fileName, string uploadPath)
{
string filePath = @"D:\UploadFile\";
if (uploadPath != null && uploadPath != "")
{
filePath = uploadPath;
}
else
{
uploadPath = filePath;
}
if (!filePath.EndsWith("\\"))
{
filePath = filePath + "\\";
}
filePath = filePath + fileName;
//FileStream fs = File.OpenRead(filePath);
if (File.Exists(filePath))
{
var fs = new FileStream(filePath, FileMode.OpenOrCreate);
CustomFileInfo fileInfo = new CustomFileInfo
{
Name = fileName,
OffSet = fs.Length,
UploadPath = uploadPath,
SendByte = new byte[fs.Length] //设置传递的数据的大小
};
fs.Position = fileInfo.OffSet;
fs.Seek(0, SeekOrigin.Begin);
fs.Read(fileInfo.SendByte, 0, fileInfo.SendByte.Length);
fs.Close();
return fileInfo;
}
return null;
}
public bool DeleteFile(string filedPath)
{
//判断文件是不是存在
if (File.Exists(filedPath))
{
//如果存在则删除
File.Delete(filedPath);
}
if (File.Exists(filedPath))
{
return false;
}
else
{
return true;
}
}
}
}
Web.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="FileTransferServicesBinding" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" maxBufferPoolSize="2147483647" transferMode="Streamed" messageEncoding="Mtom" sendTimeout="01:30:00">
<readerQuotas maxArrayLength="2147483647" maxStringContentLength="2147483647" maxBytesPerRead="2147483647"/>
</binding>
</basicHttpBinding>
</bindings>
<services>
<service behaviorConfiguration="WebApplication1.ServiceFileBehavior" name="UploadFile.ServiceFile">
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="FileTransferServicesBinding" contract="UploadFile.IServiceFile"/>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="WebApplication1.ServiceFileBehavior">
<dataContractSerializer maxItemsInObjectGraph="2147483647"/>
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
<system.web>
<compilation debug="true"/>
</system.web>
</configuration>
此时服务端代码已经完成,可以利用IIS进行发布(具体的发布过程我也不怎么会)
后边就是在自己的本地去调用这个服务
1.首先在自己的程序中添加服务引用
VS会自动生成代码。
UpLoadOrDownLoadHelper.cs
using DesktopPlugin.ServiceReference1;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DesktopPlugin.DizhiQuery
{
public class UpLoadOrDownLoadHelper
{
public bool UploadFile(string path, string servicePath)
{
//string path = @"C:\Users\admin\Desktop\培训流程.docx";
System.IO.FileInfo fileInfoIO = new System.IO.FileInfo(path);
// 要上传的文件地址
FileStream fs = File.OpenRead(fileInfoIO.FullName);
// 实例化服务客户的
//此处是例外一种实例化的方式
/*BasicHttpBinding tc = new BasicHttpBinding();
tc.TransferMode = TransferMode.Streamed;
tc.MessageEncoding = WSMessageEncoding.Mtom;
ServiceFileClient client = new ServiceFileClient(tc, new EndpointAddress("http://IP:80/ServiceFile.svc"));*/
ServiceFileClient client = new ServiceFileClient();
try
{
int maxSiz = 1024 * 100;
// 根据文件名获取服务器上的文件
CustomFileInfo file = client.GetFileInfo(fileInfoIO.Name, servicePath);
if (file != null)
{
MessageBoxButtons messButton = MessageBoxButtons.OKCancel;
DialogResult dr = MessageBox.Show("文件已经存在,确定要覆盖吗?", "提示", messButton);
if (dr == DialogResult.OK)
{
file.Name = fileInfoIO.Name;
file.Length = fs.Length;
file.UploadPath = servicePath;
while (file.Length != file.OffSet)
{
file.SendByte = new byte[file.Length - file.OffSet <= maxSiz ? file.Length - file.OffSet : maxSiz]; //设置传递的数据的大小
fs.Position = file.OffSet; //设置本地文件数据的读取位置
fs.Read(file.SendByte, 0, file.SendByte.Length);//把数据写入到file.Data中
file = client.UpLoadFileInfo(file); //上传
//int percent = (int)((double)file.OffSet / (double)((long)file.Length)) * 100;
int percent = (int)(((double)file.OffSet / (double)((long)file.Length)) * 100);
// (sender as BackgroundWorker).ReportProgress(percent);
}
}
}
else
{
file = new CustomFileInfo();
file.OffSet = 0;
file.Name = fileInfoIO.Name;
file.Length = fs.Length;
file.UploadPath = servicePath;
while (file.Length != file.OffSet)
{
file.SendByte = new byte[file.Length - file.OffSet <= maxSiz ? file.Length - file.OffSet : maxSiz]; //设置传递的数据的大小
fs.Position = file.OffSet; //设置本地文件数据的读取位置
fs.Read(file.SendByte, 0, file.SendByte.Length);//把数据写入到file.Data中
file = client.UpLoadFileInfo(file); //上传
//int percent = (int)((double)file.OffSet / (double)((long)file.Length)) * 100;
int percent = (int)(((double)file.OffSet / (double)((long)file.Length)) * 100);
// (sender as BackgroundWorker).ReportProgress(percent);
}
// 移动文件到临时目录(此部分创建可以使用sqlserver数据库代替)
// string address = string.Format(@"{0}\{1}", "d:", file.Name);
//fileInfoIO.CopyTo(address, true);
//LoadUpLoadFile(); // 上传成功重新加载文件
//e.Result = true;
}
}
catch (Exception)
{
return false;
}
finally
{
fs.Close();
fs.Dispose();
client.Close();
client.Abort();
}
return true; ;
}
public bool DownLoadFile(string fileName, string servicePath, string path)
{
ServiceFileClient client = new ServiceFileClient();
FileStream fs = null;
BinaryWriter binaryWriter = null;
try
{
CustomFileInfo fileInfo = client.GetFileInfo(fileName, servicePath);
fs = new FileStream(path, FileMode.OpenOrCreate);
long offSet = fileInfo.OffSet;
binaryWriter = new BinaryWriter(fs, Encoding.UTF8);
binaryWriter.Seek(0, SeekOrigin.Begin);
binaryWriter.Write(fileInfo.SendByte);
fileInfo.OffSet = fs.Length;
fileInfo.SendByte = null;
}
catch (Exception)
{ return false; }
finally
{
if (binaryWriter != null) { binaryWriter.Close(); }
if (fs != null) { fs.Close(); fs.Dispose(); }
client.Close();
client.Abort();
}
return true;
}
public bool DeleteServiceFile(string filePath)
{
ServiceFileClient client = new ServiceFileClient();
return client.DeleteFile(filePath);
}
}
}
参考其他网络文章写的,至于地址忘了,百度应该可以找的到。