您的位置:首页 > 其它

.net 写文件上传下载webservice

2013-04-11 10:32 531 查看
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 = "http://tempuri.org/")]

[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);否则下载回来的文件数据会有丢失。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: