// 首先我们需要自己写一个服务 来用文件流的方式传输文件
--------------------------------------------------------------------------------------
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.IO;
namespace test
{
/// <summary>
/// Summary description for UpLoad
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class UpLoad : System.Web.Services.WebService
{
/// <summary>
/// 下载文件
/// </summary>
/// <param name="filePath">文件路径</param>
/// <returns>返回文件流</returns>
[WebMethod]
public byte[] DownloadFile(string path)
{
FileStream fs = null;
path = Server.MapPath(path);
if (File.Exists(path))
{
try
{
///打开现有文件以进行读取。
//fs = File.OpenRead(path);
fs = File.OpenRead(path);
return ConvertStreamToByteBuffer(fs);
}
catch (Exception ex)
{
return new byte[0];
}
finally
{
fs.Close();
}
}
else
{
return new byte[0];
}
}
/// <summary>
/// 把给定的文件流转换为二进制字节数组。
/// </summary>
/// <param name="stream">文件流</param>
/// <returns>返回二进制数组</returns>
public static byte[] ConvertStreamToByteBuffer(System.IO.Stream stream)
{
int b1;
System.IO.MemoryStream tempStream = new System.IO.MemoryStream();
while ((b1 = stream.ReadByte()) != -1)
{
tempStream.WriteByte(((byte)b1));
}
return tempStream.ToArray();
}
}
}
--------------------------------------------------------------------------------------
public partial class Form1 : Form
{
localhost.UpLoad lws = new DownLoad.localhost.UpLoad();
public Form1()
{
InitializeComponent();
this.Load += new EventHandler(Form1_Load);
}
private void Form1_Load(object sender, EventArgs e)
{
DownloadImage();
}
/// <summary>
/// 下载附件
/// </summary>
/// <param name="attachments"></param>
/// <returns></returns>
private void DownloadImage()
{
string path = @"image\22.rar";//服务器文件路径(WEb服务的虚拟文件夹)
string directoryPath = @"d:\客户端";//本地文件夹路径
string downloadPath = @"d:\客户端\22.rar";//本地文件路径
try
{
byte[] bytes = lws.DownloadFile(path);
if (bytes != null)
{
if (!Directory.Exists(directoryPath)) { Directory.CreateDirectory(directoryPath); }//如果不存在完整的上传路径就创建
FileInfo downloadInfo = new FileInfo(directoryPath);
if (downloadInfo.IsReadOnly) { downloadInfo.IsReadOnly = false; }
//定义并实例化一个内存流,以存放提交上来的字节数组。
MemoryStream ms = new MemoryStream(bytes);
//定义实际文件对象,保存上载的文件。
FileStream fs = new FileStream(downloadPath, FileMode.Create);
///把内内存里的数据写入物理文件
ms.WriteTo(fs);
fs.Flush();
ms.Flush();
ms.Close();
fs.Close();
fs = null;
ms = null;
}
}
catch(Exception ex)
{
throw ex;
}
}
}
--------------------------------------------------------------------------------------------