asp教程.net c#利用FtpWebRequest上传下载文件实例
根据uri创建FtpWebRequest对象
FtpWebRequest ftpReq = (FtpWebRequest)FtpWebRequest.Create(new Uri(strUri));
// ftp用户名和密码
ftpReq.Credentials = new NetworkCredential("用户名", "密码");
// 指定执行什么命令
ftpReq.Method = WebRequestMethods.Ftp.UploadFile;
//成功执行一个命令后连接被关闭
ftpReq.KeepAlive = false;
//指定数据传输类型为二进制
ftpReq.UseBinary = true;
//上传文件时通知服务器文件的大小
ftpReq.ContentLength = fi.Length;
// 缓冲大小设置为2kb
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
try
{
//打开一个文件流去读上传的文件
FileStream fs = fi.OpenRead();
//把上传的文件写入流
Stream strm = ftpReq.GetRequestStream();
//每次读文件流的2kb
contentLen = fs.Read(buff, 0, buffLength);
while (contentLen != 0) // 流内容没有结束
{
// 把内容从file stream 写入 upload stream
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
strm.Close();
fs.Close();
}
catch (Exception e)
{
}
'方法二
FileInfo file = new FileInfo("G:/www.111cn.net/室内设计01.jpg");
if (file.Exists)
{
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode(file.Name));
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.Filter.Close();
Response.WriteFile(file.FullName);
Response.End();
}
|