ftp_get_file_and_directory




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
ftp_get_file_and_directory的更多相关文章
随机推荐
- Linux一些命令
1.查看系统安装软件 rpm -qa //(不包括绿色安装的软件程序,也就是直接在安装目录中启动的不包括) rpm -qa |grep gcc 参数解释:q ——询问 a —— 查询全部 l — ...
- JavaBean,List,Map转成json格式
public class User { private String username; private String password; public String getUsername() { ...
- sqlserver2008用bat脚本备份时报错因为库名有中横杠【原创】
提示原因是数据库名字有中横岗“-” 解决方法:用中括号把名字括起来就可以了 call :backupone [数据库名-new] 完整备份脚本如下 @ECHO ON set DATE=%date:/= ...
- 10、桥接模式(Bridge)
桥接模式就是把事物和其具体实现分开,使他们可以各自独立的变化.桥接的用意是:将抽象化与实现化解耦,使得二者可以独立变化,像我们常用的JDBC桥DriverManager一样,JDBC进行连接数据库的时 ...
- Android Security
Android Security¶ 确认签名¶ Debug签名: $ jarsigner -verify -certs -verbose bin/TemplateGem.apk sm 2525 Sun ...
- C#排列组合类
//----------------------------------------------------------------------------- // // 算法:排列组合类 // // ...
- NDK常用命令
NDK Build 用法(NDK Build) 1.ndk-build的用法 Android NDKr4引入了一个新的.小巧的shell脚本ndk-build,来简化源码编译. 该文件位于NDK根 ...
- 转:使用WITH AS提高性能简化嵌套SQL
使用WITH AS提高性能简化嵌套SQL 一.WITH AS的含义 WITH AS短语,也叫做子查询部分(subquery factoring),可以让你做很多事情,定义一个SQL片断,该SQL片 ...
- PAT (Advanced Level) 1077. Kuchiguse (20)
最长公共后缀.暴力. #include<cstdio> #include<cstring> #include<cmath> #include<vector&g ...
- HDU 5522 Numbers
水题 #include<cstdio> #include<cstring> #include<cmath> #include<algorithm> us ...