class DirectoryItem
{
public Uri BaseUri;
public string AbsolutePath
{ get { return string.Format("{0}/{1}", BaseUri, Name); } }
public DateTime DateCreated;
public bool IsDirectory;
public string Name;
public List<DirectoryItem> Items;
public override string ToString() { return Name; }
} internal enum enumFolderListFMT { UNIX, DOS_IIS };
internal enum enumFTPPlatform { WindowsServer2008, ServU}
/// <summary>
/// 获取目录信息(包含文件夹,文件)
/// </summary>
/// <param name="address"></param>
/// <param name="username"></param>
/// <param name="password"></param>
/// <returns></returns>
static List<DirectoryItem> GetDirectoryInformation(string addr2, string username, string password)
{
var address = addr2.EndsWith("/") ? addr2.Substring(, addr2.Length - ) : addr2;//去除最后一个斜杠
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(address);
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
request.Credentials = new NetworkCredential(username, password);
request.UsePassive = true;
request.UseBinary = true;
request.KeepAlive = false; string[] list = null;
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
list = reader.ReadToEnd().Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
} //unix or dos_iis format?
enumFolderListFMT folderFormat = enumFolderListFMT.UNIX;
int dir_pos = ;
bool found = false;
foreach (var item in list)
{
if (item.ToLower().Contains("<dir>"))
{
folderFormat = enumFolderListFMT.DOS_IIS;
dir_pos = item.ToLower().IndexOf("<dir>");
found = true;
break;
}
}
if (!found && list.Length > && list[].ToLower()[] != 'd' && list[].ToLower()[] != '-')
{
folderFormat = enumFolderListFMT.DOS_IIS;
} enumFTPPlatform ftpPlatform = enumFTPPlatform.WindowsServer2008;
if (folderFormat == enumFolderListFMT.UNIX)
{
if (list.Length > && list[].Substring(, ).ToLower().Count(c => c == '-') < )
ftpPlatform = enumFTPPlatform.WindowsServer2008;
else
ftpPlatform = enumFTPPlatform.ServU;
} List<DirectoryItem> returnValue = new List<DirectoryItem>();
if (folderFormat == enumFolderListFMT.DOS_IIS)
{
foreach (var item in list)
{
if (item.ToLower().Contains("<dir>"))
{
var dir = item.Substring(dir_pos + ).Trim();
if (dir == "." || dir == "..") continue; var di = new DirectoryItem();
di.BaseUri = new Uri(address);
//di.DateCreated = dateTime;
di.IsDirectory = true;
di.Name = dir;
//Debug.WriteLine(di.AbsolutePath);
di.Items = GetDirectoryInformation(di.AbsolutePath, username, password);
returnValue.Add(di);
}
else
{
string filename = "";
if(found)
filename = item.Substring(dir_pos + ).Trim();
else
filename = item.Substring().Trim();
var di = new DirectoryItem();
di.BaseUri = new Uri(address);
di.IsDirectory = false;
di.Name = filename;
di.Items = null;
returnValue.Add(di);
}
}
}
else if (folderFormat == enumFolderListFMT.UNIX)
{
var pos = ftpPlatform == enumFTPPlatform.WindowsServer2008 ? : ;
foreach (var item in list)
{
if (item.Substring(, ).ToLower() == "d")
{
var dir = item.Substring(pos).Trim();
if (dir == "." || dir == "..") continue;
var di = new DirectoryItem();
di.BaseUri = new Uri(address);
di.IsDirectory = true;
di.Name = dir;
di.Items = GetDirectoryInformation(di.AbsolutePath, username, password);
returnValue.Add(di);
}
else if (item.Substring(, ).ToLower() == "-")
{
var filename = item.Substring(pos).Trim();
var di = new DirectoryItem();
di.BaseUri = new Uri(address);
di.IsDirectory = false;
di.Name = filename;
di.Items = null;
returnValue.Add(di);
}
}
}
return returnValue;
} /// <summary>
/// 下载文件
/// </summary>
/// <param name="filePath">下载到哪里</param>
/// <param name="outputFilename">下载后的文件名</param>
/// <param name="fileName">服务器上的文件名</param>
/// <param name="ftpServerIP">服务器全路径,注意最后的斜线不可少。如ftp://172.18.1.152:8009/aaa/</param>
/// <param name="ftpUserID">访问的用户名</param>
/// <param name="ftpPassword">访问的密码</param>
/// <returns></returns>
public int DownloadFile(string filePath, string outputFilename, string fileName, string ftpServerIP, string ftpUserID, string ftpPassword)
{
FtpWebRequest reqFTP;
try
{
//filePath = < <The full path where the file is to be created.>>,
//fileName = < <Name of the file to be created(Need not be the name of the file on FTP server).>>
FileStream outputStream = new FileStream(filePath + "\\" + outputFilename, FileMode.Create); reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpServerIP + fileName));
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.KeepAlive = false;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
long cl = response.ContentLength;
int bufferSize = ;
int readCount;
byte[] buffer = new byte[bufferSize]; readCount = ftpStream.Read(buffer, , bufferSize);
while (readCount > )
{
outputStream.Write(buffer, , readCount);
readCount = ftpStream.Read(buffer, , bufferSize);
}
ftpStream.Close();
outputStream.Close();
response.Close();
return ;
}
catch (Exception ex)
{
// Logging.WriteError(ex.Message + ex.StackTrace);
System.Windows.Forms.MessageBox.Show(ex.Message);
return -;
}
}
get_directory_file_download