public class FtpHelper
{
public FtpHelper(string p_url, string p_user, string p_password)
{
if (!p_url.ToUpper().StartsWith("FTP:"))
{
Url = "ftp://" + p_url;
}
else
{
Url = p_url;
}
User = p_user;
Password = p_password;
} public string Url { get; private set; } public string User { get; private set; } public string Password { get; private set; } public FtpWebRequest CreateConnect(string p_uri)
{
FtpWebRequest reqFTP; // 根据uri创建FtpWebRequest对象
reqFTP = (FtpWebRequest)WebRequest.Create(new Uri(p_uri)); // ftp用户名和密码
reqFTP.Credentials = new NetworkCredential(User, Password); return reqFTP;
} /// <summary>
/// 上传文件
/// </summary>
/// <param name="p_uri">ftp地址 ex=ftp://192.168.100.5//tmp// 切记要以//结尾</param>
/// <param name="p_filename">文件路径地址绝对路径 ex:C:\\Users\ligl\\Desktop\\1.txt</param>
/// <param name="isDelete"></param>
/// <returns></returns>
public bool Upload(string p_uri, string p_filename, bool isDelete = false)
{
var fileInf = new FileInfo(p_filename);
string uri = Path.Combine(p_uri, fileInf.Name); FtpWebRequest reqFTP = CreateConnect(uri);
// 默认为true,连接不会被关闭
// 在一个命令之后被执行
reqFTP.KeepAlive = false; // 指定执行什么命令
reqFTP.Method = WebRequestMethods.Ftp.UploadFile; // 指定数据传输类型
reqFTP.UseBinary = true; // 上传文件时通知服务器文件的大小
reqFTP.ContentLength = fileInf.Length + ; // 缓冲大小设置为2kb
int buffLength = ; var buff = new byte[buffLength];
int contentLen; // 打开一个文件流 (System.IO.FileStream) 去读上传的文件
FileStream fs = fileInf.OpenRead();
try
{
// 把上传的文件写入流
Stream strm = reqFTP.GetRequestStream(); // 每次读文件流的2kb
contentLen = fs.Read(buff, , buffLength); // 流内容没有结束
while (contentLen != )
{
// 把内容从file stream 写入 upload stream
strm.Write(buff, , contentLen); contentLen = fs.Read(buff, , buffLength);
} // 关闭两个流
strm.Close();
fs.Close(); var uploadResponse = (FtpWebResponse)reqFTP.GetResponse();
if (File.Exists(p_filename) && isDelete)
{
File.Delete(p_filename);
}
return (uploadResponse.StatusDescription.StartsWith(""));
}
catch (Exception ex)
{
//System.Windows.MessageBox.Show(ex.Message, "Upload Error");
throw ex;
}
} public bool Delete(string p_filename)
{
var fileInf = new FileInfo(p_filename);
string uri = Path.Combine(Url, fileInf.Name); try
{
var listRequest = (FtpWebRequest)WebRequest.Create(new Uri(uri)); listRequest.Method = WebRequestMethods.Ftp.DeleteFile; listRequest.Credentials = new NetworkCredential(User, Password); var listResponse = (FtpWebResponse)listRequest.GetResponse(); return (listResponse.StatusDescription.StartsWith(""));
}
catch (Exception ex)
{
throw ex;
}
} public bool MakeDir(string p_uri)
{
try
{
string url = Url;
if (string.IsNullOrEmpty(url))
{
return false;
} char lastChar = url[url.Length - ];
if (lastChar != '\\' && lastChar != '/')
{
url += '\\';
} string dir = p_uri.Remove(, url.Length); string[] dirs = dir.Split(new[] { Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar },
StringSplitOptions.RemoveEmptyEntries); dir = CreateDir(dirs); return CreateMackDir(url, dir);
}
catch (Exception ex)
{
throw ex;
}
} public string CreateDir(string[] p_dirNames)
{
var sb = new StringBuilder(); foreach (string dir in p_dirNames)
{
sb.Append(dir);
sb.Append("\\");
} return sb.ToString();
} public string GetFirstDir(string p_dir)
{
string[] dirs = p_dir.Split(new[] { Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar },
StringSplitOptions.RemoveEmptyEntries); if (dirs.Length > )
{
return dirs[];
} return string.Empty;
} public string RemvoeDirFromFirst(string p_longDir, string p_firstDir)
{
string value = p_longDir.Remove(, p_firstDir.Length + ); return value;
} private bool CreateMackDir(string p_url, string p_dir)
{
string dir = GetFirstDir(p_dir); if (string.IsNullOrEmpty(dir))
{
return true;
} string newurl = Path.Combine(p_url, dir);
if (!IsExsit(p_url, dir))
{
try
{
FtpWebRequest reqFtp = CreateConnect(newurl);
reqFtp.Method = WebRequestMethods.Ftp.MakeDirectory;
var response = (FtpWebResponse)reqFtp.GetResponse();
response.Close();
}
catch (Exception ex)
{
throw ex;
}
} string newdir = RemvoeDirFromFirst(p_dir, dir);
CreateMackDir(newurl, newdir); return true;
} public bool IsExsit(string p_url, string p_dir)
{
string[] list = GetFileList(p_url, WebRequestMethods.Ftp.ListDirectory); if (list == null || list.Length == )
{
return false;
} return list.Contains(p_dir);
} private string[] GetFileList(string path, string WRMethods) //上面的代码示例了如何从ftp服务器上获得文件列表
{
var result = new StringBuilder(); try
{
string tempPath = path;
if (!path.EndsWith("/"))
{
tempPath += "/";
} FtpWebRequest reqFtp = CreateConnect(tempPath);
reqFtp.Method = WRMethods;
WebResponse response = reqFtp.GetResponse();
var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); //中文文件名
string line = reader.ReadLine();
while (line != null)
{
result.Append(line);
result.Append("\n");
line = reader.ReadLine();
}
// to remove the trailing '/n'
if (result.Length > )
{
result.Remove(result.ToString().LastIndexOf('\n'), );
}
reader.Close();
response.Close();
return result.ToString().Split('\n');
}
catch (Exception ex)
{
throw ex;
}
}
}