一次闲的无聊做的上传功能 , 下载等其他功能尚未作出(注释代码中都有 , 这里不再 一 一 解释) , 下次补出 。 但这个方法有个很不好的地方 , 如果是循环上传文件的话 , 那么 , ftp连接会断开 , 然后循环到下次上传文件时 , 再次重新连接 , 依次循环。这样的话 , 就会导致效率十分的低 , 但是好的方法 , 请原谅我这个小菜鸟还写不出来 , 如果有懂得人看到这篇文章 , 欢迎指点!
//ftp上传帮助类
public class FtpHelper
{
string ftpServerIP;
string ftpRemotePath;
string ftpUserID;
string ftpPassword;
string ftpURI;
/// <summary>
/// 连接FTP
/// </summary>
/// <param name="FtpServerIP">FTP连接地址</param>
/// <param name="ftpPort">FTP端口</param>
/// <param name="FtpUserID">用户名</param>
/// <param name="FtpPassword">密码</param>
public FtpHelper(string FtpServerIP, string ftpPort, string FtpUserID, string FtpPassword)
{
ftpServerIP = FtpServerIP;
ftpUserID = FtpUserID;
ftpPassword = FtpPassword;
ftpURI = "ftp://" + ftpServerIP + ":" + ftpPort + "/";
}
/// <summary>
/// 上传
/// </summary>
/// <param name="filename">上传的文件名</param>
public bool Upload(string filename)
{
try
{
FileInfo fileInf = new FileInfo(filename.Split('*')[1]);
//HttpUtility.UrlEncode(为了防止有$符号之类的文件 , 导致出现意外的情况)
string uri = ftpURI + filename.Split('*')[0] + HttpUtility.UrlEncode(fileInf.Name, System.Text.Encoding.UTF8);
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
reqFTP.UseBinary = true;
reqFTP.UsePassive = true;//被动模式(这个要和搭建的ftp服务对应)
reqFTP.ContentLength = fileInf.Length;
reqFTP.Timeout = 1000 * 60 * 5;//响应请求等待的时间
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
FileStream fs = fileInf.OpenRead();
try
{
using (Stream strm = reqFTP.GetRequestStream())
{
contentLen = fs.Read(buff, 0, buffLength);
while (contentLen != 0)
{
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
}
fs.Close();
return true;
}
catch (Exception ex)
{
fs.Close();
LogMessage("Ftphelper Upload Error" + fileInf.FullName + "--> " + ex.Message);
return false;
}
}
catch (Exception ex)
{
LogMessage("Ftp Upload Error,初始化目录错误 --> " + ex.Message);
return false;
}
}
}
//调用上传类方法
static void Main(string[] args)
{
//实例化ftp
FtpHelper ftp = new FtpHelper(ip, port, uid, pwd);
//参数upload_path 为上传ftp的路径 , filePath为上传文件的本地绝对路径
ftp.Upload(upload_path + "*" + filePath);
}