protected void Page_Load(object sender, EventArgs e) { //SpiderLib.DownloadFtp ftl = new DownloadFtp("ftp://172.16.32.189:21/123.txt", "imyang", ""); //Response.Write("<br/><br/><br/><strong>已经下载了FTP返回信息FtpWebResponse</strong>"); SpiderLib.FTPClient ft = new FTPClient("172.16.32.158", "/", "Anonymous", "", 21); ft.Connect(); foreach (string str in ft.Dir("*.rar")) { Response.Write(str.ToString() + "<br/>"); } }
public static void Initialize() { if (!(Utilites.IsNullOrEmpty(Properties.Settings.Default.FTPUploadPath) || Utilites.IsNullOrEmpty(Properties.Settings.Default.FTPAddress) || Utilites.IsNullOrEmpty(Properties.Settings.Default.FTPUsername))) { var credentials = new NetworkCredential(Properties.Settings.Default.FTPUsername, Utilites.StringCipher.Decrypt(Properties.Settings.Default.FTPPassword, "TorrentFlow")); ftpClient = new FTPClient(); var host = Properties.Settings.Default.FTPAddress; if (!host.StartsWith("ftp://")) { host = "ftp://" + host; } if (Properties.Settings.Default.FTPPort != 0) { host = String.Format("{0}:{1}", host, Properties.Settings.Default.FTPPort.ToString()); } ftpClient.Host = host; ftpClient.Credentials = credentials; ftpClient.EncryptionMode = Properties.Settings.Default.FTPEncryptionMode; } else { pi.Notify("Not Uploading", "No FTP server configured.", 3000); } if (!Utilites.IsNullOrEmpty(Properties.Settings.Default.WatchDirectory)) { watcher = new DirectoryWatcher(Properties.Settings.Default.WatchDirectory, NewTorrentFileDetected, NotifyFilters.LastWrite | NotifyFilters.CreationTime); watcher.SetFilter("*.torrent"); watcher.Start(); } else { pi.Notify("Not Watching", "TorrentFlow is not watching for torrent files.", 3000); } if (!Utilites.IsNullOrEmpty(Properties.Settings.Default.DownloadDirectory)) { //ftpClient.DownloadStatusChanged += OnDownloadStatusChanged; StartTimer(); } else { pi.Notify("Not Downloading", "TorrentFlow will not download any files.", 3000); } }
/// <summary> /// Test harness /// </summary> public static void Main(string[] args) { // we want remote host, user name and password if (args.Length < 3) { Usage(); System.Environment.Exit(1); } Logger log = Logger.GetLogger(typeof(Demo)); // assign args to make it clear string host = args[0]; string user = args[1]; string password = args[2]; Logger.CurrentLevel = Level.ALL; FTPClient ftp = null; try { // set up client log.Info("Connecting"); ftp = new FTPClient(host); // login log.Info("Logging in"); ftp.Login(user, password); // set up passive ASCII transfers log.Debug("Setting up passive, ASCII transfers"); ftp.ConnectMode = FTPConnectMode.PASV; ftp.TransferType = FTPTransferType.ASCII; // get directory and print it to console log.Debug("Directory before put:"); string[] files = ftp.Dir(".", true); for (int i = 0; i < files.Length; i++) log.Debug(files[i]); // copy file to server log.Info("Putting file"); ftp.Put("readme.txt", "readme.txt"); // get directory and print it to console log.Debug("Directory after put"); files = ftp.Dir(".", true); for (int i = 0; i < files.Length; i++) log.Debug(files[i]); // copy file from server log.Info("Getting file"); ftp.Get("readme.txt.copy", "readme.txt"); // delete file from server log.Info("Deleting file"); ftp.Delete("readme.txt"); // get directory and print it to console log.Debug("Directory after delete"); files = ftp.Dir("", true); for (int i = 0; i < files.Length; i++) log.Debug(files[i]); // Shut down client log.Info("Quitting client"); ftp.Quit(); log.Info("Test complete"); } catch (Exception e) { log.Debug(e.StackTrace); } }
/// <summary> /// Качва файл на FTP /за един файл/ /// </summary> private void UploadFile(string aFile) { using (FTPClient ftpClnt = new FTPClient()) { ftpClnt.Hostname = this.FTP_Hostname; ftpClnt.Username = this.FTP_Username; ftpClnt.Password = this.FTP_Password; // string lFile = Path.Combine(Path.Combine(_ApplPath, "send_news"), aFile); string tFile = dUtils.UrlCombine(this.FTP_UpdateDir, aFile); ftpClnt.Upload(lFile, tFile); } }
/// <summary> /// Качва новините на сайта /// </summary> private void UpdateXMLNews() { SetMessage(LogMessageType.Event, "UpdateXMLNews: Start"); using (FTPClient ftpClnt = new FTPClient()) { ftpClnt.Hostname = this.FTP_Hostname; ftpClnt.Username = this.FTP_Username; ftpClnt.Password = this.FTP_Password; SetMessage(LogMessageType.Event, "UpdateXMLNews: news.xml"); ftpClnt.Upload(_ApplPath_NewsXML, dUtils.UrlCombine(this.FTP_UpdateDir, "news.xml")); SetMessage(LogMessageType.Event, "UpdateXMLNews: news_info.xml"); ftpClnt.Upload(_ApplPath_NewsInfoXML, dUtils.UrlCombine(this.FTP_UpdateDir, "news_info.xml")); SetMessage(LogMessageType.Event, "UpdateXMLNews: enclosure.xml"); ftpClnt.Upload(_ApplPath_EnclosureXML, dUtils.UrlCombine(this.FTP_UpdateDir, "enclosure.xml")); } SetMessage(LogMessageType.Event, "UpdateXMLNews: Done"); }
/**/ /// <summary> /// 在下载结束后清空程序目录的多余文件 /// </summary> private static void ClearFolder() { string folder = Environment.CurrentDirectory; string[] dictorys = Directory.GetFiles(folder); foreach (string dictory in dictorys) { FileInfo info = new FileInfo(dictory); if (info.Length == 0) File.Delete(dictory); } } /**/ /// <summary> /// 递归获取ftp文件夹的内容 /// </summary> /// <param name="fileMark">文件标记</param> /// <param name="path">远程路径</param> /// <param name="client"></param> /// <param name="folder"></param> private static void GetFolder(string fileMark, string path, FTPClient client, string folder, DateTime currentDate) { string[] dirs = client.Dir(path); //获取目录下的内容 client.ChDir(path); //改变目录 foreach (string dir in dirs) { string[] infos = dir.Split(' '); //string info = infos[infos.Length - 1].Replace("\r", ""); string info = getFileName(dir.Replace("\r", "")); if (dir.StartsWith("d") && !string.IsNullOrEmpty(dir)) //为目录 { if (!info.EndsWith(".") && !info.EndsWith("..")) //筛选出真实的目录 { Directory.CreateDirectory(folder + "\\" + info); GetFolder(fileMark, path + "/" + info, client, folder + "\\" + info, currentDate); client.ChDir(path); } } else if (dir.StartsWith("-r")) //为文件 { string file = folder + "\\" + info; if (File.Exists(file)) { long remotingSize = client.GetFileSize(info); FileInfo fileInfo = new FileInfo(file); long localSize = fileInfo.Length; if (remotingSize != localSize) //短点续传 { client.GetBrokenFile(info, folder, info, localSize); } } else { //由于FTP有滞后,所以需要多取一天的数据 if (info.StartsWith("BRK.PCNT.Site Name." + currentDate.ToString("yyMMdd")) || info.StartsWith("BRK.PCNT.Site Name." + currentDate.AddDays(1).ToString("yyMMdd"))) { client.GetFile(info, folder, info); //下载文件 Console.WriteLine("文件" + folder + info + "已经下载"); } } } } }
private void GetFTPData(DateTime currentDate) { m_localFolder = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "temp/BI_CustomerFlow/FTPData/" + currentDate.ToShortDateString(); FTPClient client = new FTPClient("192.168.0.26", "", "jk", "jk654@123", 21); client.Connect(); GetFolder("*", ".ep01", client, CreateFolder(), currentDate); //由于 FTP的数据有滞后,所以需要缓冲一天的数据 //GetFolder("*", ".ep01", client, CreateFolder(), "BRK.PCNT.Site Name." + currentDate.AddDays(1).ToString("yyMMdd")); client.DisConnect(); //ClearFolder() Console.WriteLine("下载完毕"); m_dtFTP = new BI_CustomerFlow.T_CustomerFlowDataTable(); m_dtFTP.Columns.Remove("Seq_No"); //获取数据 foreach (string strFileName in Directory.GetFiles(m_localFolder)) { FileStream fs = new FileStream(strFileName, FileMode.Open, FileAccess.Read); byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, (Int32)fs.Length); fs.Close(); fs.Close(); fs.Close(); fs.Dispose(); fs.Dispose(); fs.Dispose(); string[] strText = Encoding.UTF8.GetString(buffer).Replace("\r\n", "\n").Split('\n'); //案例数据:25||Site ID||New Zone0|2|09/11/2013 04:00:00|1|1|160|159|192.168.254.2| foreach (string strRow in strText) { if (strRow == "") { continue; } string strTemp = ""; if (strRow.Substring(strRow.Length - 1) == "|") { strTemp = strRow.Substring(0, strRow.Length - 1); } string[] str = (System.Guid.NewGuid().ToString() + "|" + strTemp).Split('|'); //错误数据 if (str.Length != 13) { continue; } if (str[7].StartsWith(currentDate.ToString("MM/dd/yyyy"))) { m_dtFTP.Rows.Add(str); } } } }
private void Connect(string url) { Uri adr = new Uri(url); hostname = adr.Host; _CheckProtocol(url); ftp = new FTPClient( adr.Host, adr.Port, "anonymous", @"*****@*****.**" ); hostname = adr.Host; }
private async void testftp_btn_Click(object sender, EventArgs e) { connectionStatus_lbl.ForeColor = Color.Black; connectionStatus_lbl.Text = "Testing..."; try { var credentials = new NetworkCredential(ftpUsername_txtBox.Text, ftpPassword_txtBox.Text); var testClient = new FTPClient(); var host = ftpAddress_txtBox.Text; if (!host.StartsWith("ftp://")) { host = "ftp://" + host; } if (ftpCustomPort_chkBox.Checked) { host = String.Format("{0}:{1}", host, ftpCustomPort_txtBox.Text); } testClient.Host = host; testClient.Credentials = credentials; testClient.EncryptionMode = ftpSSL_rdoBtn.Checked ? EncryptionMode.SSL : EncryptionMode.None; var success = await testClient.TestConnection(ftpDownloadPath_txtBox.Text); if (success) { connectionStatus_lbl.ForeColor = Color.Green; connectionStatus_lbl.Text = "Connected"; } else { throw new Exception(); } } catch (Exception ex) { //TODO: not sure if we should display this, log it, both, or neither. connectionStatus_lbl.ForeColor = Color.Red; connectionStatus_lbl.Text = "Disconnected"; } }
/// <summary> /// �ϴ��ļ� /// </summary> /// <param name="ftpFolder">ftpĿ¼</param> /// <param name="ftpFileName">ftp�ļ���</param> public bool PutFile(string ftpFolder, string ftpFileName) { try { if (ftp == null) ftp = this.getFtpClient(); if (!ftp.Connected) { ftp.Connect(); ftp.ChDir(ftpFolder); } ftp.Put(ftpFileName); return true; } catch { return false; } }
/// <summary> /// �õ��ļ��б� /// </summary> /// <returns></returns> public string[] GetList(string strPath) { if (ftp == null) ftp = this.getFtpClient(); ftp.Connect(); ftp.ChDir(strPath); return ftp.Dir("*"); }
/// <summary> ///�õ�FTP������� /// </summary> public FTPClient getFtpClient() { FTPClient ft = new FTPClient(); ft.RemoteHost = this.Server; ft.RemoteUser = this.User; ft.RemotePass = this.Pass; return ft; }
/// <summary> /// �����ļ� /// </summary> /// <param name="ftpFolder">ftpĿ¼</param> /// <param name="ftpFileName">ftp�ļ���</param> /// <param name="localFolder">����Ŀ¼</param> /// <param name="localFileName">�����ļ���</param> public bool GetFileNoBinary(string ftpFolder, string ftpFileName, string localFolder, string localFileName) { try { if (ftp == null) ftp = this.getFtpClient(); if (!ftp.Connected) { ftp.Connect(); ftp.ChDir(ftpFolder); } ftp.GetNoBinary(ftpFileName, localFolder, localFileName); return true; } catch { try { ftp.DisConnect(); ftp = null; } catch { ftp = null; } return false; } }
/// <summary> /// �õ��ļ��б� /// </summary> /// <param name="ftpFolder">FTPĿ¼</param> /// <returns>FTPͨ�����</returns> public string[] GetFileList(string ftpFolder, string strMask) { string[] strResult; try { if (ftp == null) ftp = this.getFtpClient(); if (!ftp.Connected) { ftp.Connect(); ftp.ChDir(ftpFolder); } strResult = ftp.Dir(strMask); return strResult; } catch { return null; } }
/// <summary> /// �õ�FTP���ļ���Ϣ /// </summary> /// <param name="ftpFolder">FTPĿ¼</param> /// <param name="ftpFileName">ftp�ļ���</param> public string GetFileInfoConnected(string ftpFolder, string ftpFileName) { string strResult = ""; try { if (ftp == null) ftp = this.getFtpClient(); if (!ftp.Connected) { ftp.Connect(); ftp.ChDir(ftpFolder); } strResult = ftp.GetFileInfo(ftpFileName); return strResult; } catch { return ""; } }
/// <summary> /// ����FTP�������Ƿ�ɵ�½ /// </summary> public bool CanConnect() { if (ftp == null) ftp = this.getFtpClient(); try { ftp.Connect(); ftp.DisConnect(); return true; } catch { return false; } }