using System; 
using System.Data; 
using System.Web; 
using System.Collections; 
using System.Web.Services; 
using System.Web.Services.Protocols; 
using System.ComponentModel; 
using System.IO; 
  
namespace UpDownFile 
{ 
    /**/ 
    /// <summary> 
    /// UpDownFile 的摘要说明 
    /// </summary> 
    [WebService(Namespace = "http://tempuri.org/")] 
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
    [ToolboxItem(false)] 
    public class UpDownFile : System.Web.Services.WebService 
    { 
        //上传文件至WebService所在服务器的方法,这里为了操作方法,文件都保存在UpDownFile服务所在文件夹下的File目录中 
        [WebMethod] 
        public bool Up(byte[] data, string filename) 
        { 
            try 
            { 
                FileStream fs = File.Create(Server.MapPath("File/") + filename); 
                fs.Write(data, 0, data.Length); 
                fs.Close(); 
                return true; 
            } 
            catch 
            { 
                return false; 
            } 
        } 
  
        //下载WebService所在服务器上的文件的方法 
        [WebMethod] 
        public byte[] Down(string filename) 
        { 
            string filepath = Server.MapPath("File/") + filename; 
            if (File.Exists(filepath)) 
            { 
                try 
                { 
                    FileStream s = File.OpenRead(filepath); 
                    return ConvertStreamToByteBuffer(s); 
                } 
                catch 
                { 
                    return new byte[0]; 
                } 
            } 
            else 
            { 
                return new byte[0]; 
            } 
        } 
    } 
} 
上传: 
  
            //FileUpload1是aspx页面的一个FileUpload控件             UpDownFile.UpDownFile up = new UpDownFile.UpDownFile();             up.Up(ConvertStreamToByteBuffer(FileUpload1.PostedFile.InputStream),             FileUpload1.PostedFile.FileName.Substring(FileUpload1.PostedFile.FileName.LastIndexOf("\\") + 1)); 
下载:             UpDownFile.UpDownFile down = new UpDownFile.UpDownFile();             byte[] file = down.Down(Request.QueryString["filename"].ToString()); //filename是要下载的文件路径,可自行以其它方式获取文件路径             Response.BinaryWrite(file); 
以下是将文件流转换成文件字节的函数(因为Stream类型的是不能直接通过WebService传输): 
 protected byte[] ConvertStreamToByteBuffer(Stream s) 
 { 
    BinaryReader br = new BinaryReader(stream); 
    byte[] fileBytes = br.ReadBytes((int)stream.Length); 
    return fileBytes; 
}   |