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; using System.Text;namespace UpDownFile
{ /// <summary> /// Service1 的摘要说明 /// </summary> [WebService(Namespace = "")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [ToolboxItem(false)] // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。 // [System.Web.Script.Services.ScriptService] public class UpDownFile : System.Web.Services.WebService { private static string filesavepath = System.Configuration.ConfigurationManager.AppSettings.Get("filepath"); /// <summary> /// 下载文件 /// </summary> /// <param name="filename"></param> /// <returns></returns> [WebMethod] public bool DownFile(string filename,out byte[] bytes) { string filepath = filesavepath + filename; LogWrite(filepath); if (File.Exists(filepath)) { try { FileStream s = File.OpenRead(filepath); bytes = ConvertStreamToByteBuffer(s); s.Close(); return true; } catch { bytes = new byte[0]; return false; } } else { bytes = new byte[0]; return false; } }public byte[] ConvertStreamToByteBuffer(Stream s)
{ MemoryStream ms = new MemoryStream(); int b; s.Seek(0, 0); while ((b = s.ReadByte()) !=-1) { ms.WriteByte((byte)b); } return ms.ToArray(); }[WebMethod]
public bool UpFile(byte[] data, string filepath, string filename) { try { filepath = filesavepath + filepath; if (!Directory.Exists(filepath)) { Directory.CreateDirectory(filepath); } if (Directory.Exists(filepath)) { string fullname = filepath + filename; if (File.Exists(fullname)) { File.Delete(fullname); } FileStream fs = File.Create(fullname); fs.Write(data, 0, data.Length); fs.Close(); return true; } else return false; } catch { return false; } }protected bool LogWrite( string content)
{ try { //读取 string file = "C:\\11111.txt"; StreamReader sr = new StreamReader(file, true); string s = sr.ReadLine(); sr.Close(); //写入 与源文件字符相加 StreamWriter sw = new StreamWriter(file, true, Encoding.UTF8); sw.WriteLine(s + content); sw.Close(); return true; } catch (Exception ex) { //Response.Write(ex.Message.ToString()); return false; } } } }
注意:一定要加 s.Seek(0, 0);否则下载回来的文件数据会有丢失。