using Microsoft.SqlServer.Server;
using System;
using System.IO;
using System.Net;
public class FtpUpDown
{
#region Ftp上传文件
/// <summary>
/// 上传文件 到FTP服务器
/// </summary>
/// <param name="ftpServerIp">服务器ip</param>
/// <param name="ftpUserID">用户名</param>
/// <param name="ftpPassword">密码</param>
/// <param name="localFile">要上传到FTP服务器的本地文件</param>
/// <param name="ftpPath">FTP地址</param>
/// <param name="result">返回结果</param>
[SqlProcedure]
public static void FtpUpLoad(string localFile, string ftpServerIp, string ftpUserID, string ftpPassword, out string result)
{
string ftpPath;
if (!File.Exists(localFile))
{
result = "文件:“" + localFile + "” 不存在!";
return;
}
FileInfo fileInfo = new FileInfo(localFile);
FtpWebRequest reqFTP;
ftpPath = "Ftp://" + ftpServerIp + "/" + fileInfo.Name;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(ftpPath);// 根据uri创建FtpWebRequest对象
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);// ftp用户名和密码
reqFTP.KeepAlive = false;// 默认为true,连接不会被关闭 // 在一个命令之后被执行
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;// 指定执行什么命令
reqFTP.UseBinary = true;// 指定数据传输类型
reqFTP.ContentLength = fileInfo.Length;// 上传文件时通知服务器文件的大小
int buffLength = 2048;// 缓冲大小设置为2kb
byte[] buff = new byte[buffLength];
int contentLen;
// 打开一个文件流 (System.IO.FileStream) 去读上传的文件
FileStream fs = fileInfo.OpenRead();
try
{
Stream strm = reqFTP.GetRequestStream();// 把上传的文件写入流
contentLen = fs.Read(buff, 0, buffLength);// 每次读文件流的2kb
while (contentLen != 0)// 流内容没有结束
{
// 把内容从file stream 写入 upload stream
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
// 关闭两个流
strm.Close();
fs.Close();
result = "文件【" + ftpPath + "/" + fileInfo.Name + "】上传成功!";
}
catch (Exception ex)
{
result = "上传文件【" + ftpPath + "/" + fileInfo.Name + "】时,发生错误:" + ex.Message;
}
}
#endregion
}