public static void CreateDirectoryEx(this FTPConnection connection, string directory) { // have to create each individual directory in the requested tree var dirFragment = directory; var dirTree = new List <string>(); while (!string.IsNullOrEmpty(dirFragment)) { var dir = Path.GetFileName(dirFragment); dirTree.Insert(0, dir); dirFragment = Path.GetDirectoryName(dirFragment); } for (var i = 0; i < dirTree.Count; i++) { var newDir = dirTree[i]; var bRet = false; try { bRet = connection.ChangeWorkingDirectory(newDir); } catch (FTPException) { } if (!bRet) { connection.CreateDirectory(newDir); connection.ChangeWorkingDirectory(newDir); } Debug.WriteLine(connection.ServerDirectory); } }
private static void DeleteDirectoryRecursively(FTPConnection ftpConnect, string remotePath) { ftpConnect.ChangeWorkingDirectory(remotePath); var files = ftpConnect.GetFileInfos().Where(x => !x.Name.Contains(".") || x.Name.Contains("jpg")); foreach (var tmp in files) { if (!tmp.Dir) { ftpConnect.DeleteFile(tmp.Name); } } // delete all subdirectories in the remotePath directory foreach (var tmp in files) { if (tmp.Dir) { DeleteDirectoryRecursively(ftpConnect, tmp.Name); } } // delete this directory ftpConnect.ChangeWorkingDirectoryUp(); ftpConnect.DeleteDirectory(remotePath); }
/// <summary> /// 获取 FTP 服务器的文件列表的递归方法 /// </summary> /// <param name="path">服务器相对路径</param> /// <param name="files">填充文件名的变量</param> /// <returns></returns> private void GetFiles(string path, IList <FtpFileInfo> files) { if (files == null) { files = new List <FtpFileInfo>(); } m_pFtp.ChangeWorkingDirectory("/" + path.TrimStart('/')); FTPFile[] listItems = m_pFtp.GetFileInfos("/" + path.TrimStart('/')); foreach (FTPFile listItem in listItems) { if (!listItem.Dir) { files.Add(new FtpFileInfo(listItem, path));//(path.TrimEnd('/') + "/").TrimStart('/') + listItem.Name); } else { GetFiles(path.TrimEnd('/') + "/" + listItem.Name, files); } } }
[TestMethod]//功能强 public void MyFtpTest1() { var ftp = new FTPConnection(); ftp.ServerAddress = "115.159.186.113"; ftp.ServerPort = 21; ftp.UserName = "******"; ftp.Password = "******"; ftp.CommandEncoding = Encoding.GetEncoding("GBK");//设置编码 //连接 ftp.Connect(); ftp.ConnectMode = FTPConnectMode.PASV; ftp.TransferType = FTPTransferType.BINARY; string[] files = ftp.GetFiles(); FTPFile[] fileDetails = ftp.GetFileInfos(); ////当前目录 string directory = ftp.WorkingDirectory; ////切换目录 进入指定的目录 bool change = ftp.ChangeWorkingDirectory("/tools/测试证书pfx/"); files = ftp.GetFiles(); fileDetails = ftp.GetFileInfos(); ////切换到上级目录 //bool b = ftp.ChangeWorkingDirectoryUp(); ////上传文件 //ftp.UploadFile(localFilePath, remoteFileName); ////上传文件 已存是否覆盖 //ftp.UploadFile(localFilePath, remoteFileName, true); ////下载文件 //ftp.DownloadFile("b2bic-副本.rar", "/tools/b2bic-副本.rar"); //将内存字节数据上传到远程服务器 //ftp.UploadByteArray(bytes, remotFileName); //下载远程文件到本地内存 //byte[] bytes = ftp.DownloadByteArray(remoteFileName); //删除远程文件 //bool dFlag = ftp.DeleteFile(remoteFileName); //内存流上传到远程服务器 //ftp.UploadStream(stream, remoteFileName); //关闭 ftp.Close(); }
public override IEnumerable <IDirectoryViewItem> GetDirectoryContent(string dirPath) { var content = new List <IDirectoryViewItem>(); if (!IsRootPath(dirPath)) { content.Add(new MoveUpObject()); } var infos = connection.GetFileInfos(dirPath); var ftpFiles = infos.Where(x => x.Name != "." && x.Name != "..").Select(x => FTPFile.CreateFromServerCall(x, dirPath, account.Id)).OrderByDescending(x => x.IsDirectory); content.AddRange(ftpFiles); connection.ChangeWorkingDirectory(dirPath); return(content); }
public static void CreateDirectory(IEnumerable <string> folderList) { var ftpConnect = new FTPConnection(); try { ftpConnect.ServerAddress = System.Configuration.ConfigurationManager.AppSettings["HostGoDaddy"].ToString(); ftpConnect.ServerPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PortGoDaddy"].ToString()); ftpConnect.UserName = System.Configuration.ConfigurationManager.AppSettings["UsernameGoDaddy"].ToString(); ftpConnect.Password = System.Configuration.ConfigurationManager.AppSettings["PasswordGoDaddy"].ToString(); ftpConnect.Connect(); ftpConnect.ChangeWorkingDirectory("/public_html"); foreach (var tmp in folderList) { if (!ftpConnect.DirectoryExists(tmp)) { ftpConnect.CreateDirectory(tmp); } } } catch (Exception ex) { throw new Exception("Exception is " + ex.Message); } finally { ftpConnect.Close(); //ftpConnect.Dispose(); } }
private bool ftpAll(string fromPath, string to, string uname, string pwd, IProgress <GFUTaskProgress> progress = null) { //if (bError) return false; string[] dirs = Directory.GetDirectories(fromPath); foreach (string d in dirs) { //if (bError) return false; string p = Path.GetFileName(d); try { WebRequest request = WebRequest.Create("ftp://" + to + "/" + p); request.Method = WebRequestMethods.Ftp.MakeDirectory; request.Credentials = new NetworkCredential(uname, pwd); request.Timeout = 5000; using (var resp = (FtpWebResponse)request.GetResponse()) { Console.WriteLine(resp.StatusCode); } } catch (Exception ex) { if (ex is WebException) { if ((ex as WebException).Status == WebExceptionStatus.ConnectFailure) { //UploadState.Progress = 0; _lastError = "Failed to connect to Gemini: " + (ex as WebException).Message; return(false); } } } string dirPath = Path.Combine(fromPath, p); string toPath = to + "/" + p; ftpAll(dirPath, toPath, uname, pwd); //string[] files = Directory.GetFiles(dirPath); //foreach (string f in files) //{ // string fname = Path.GetFileName(f); // using (WebClient webClient = new WebClient()) // { // webClient.Credentials = new NetworkCredential(uname, pwd); // webClient.UploadFile("ftp://" + toPath + "/" + fname, f); // } //} } #if false { try { string[] files2 = Directory.GetFiles(fromPath); EnterpriseDT.Net.Ftp.FTPConnection ftpConnection = new FTPConnection(); ftpConnection.ServerAddress = txtIP.Text; ftpConnection.UserName = uname; ftpConnection.Password = "******"; ftpConnection.AccountInfo = ""; ftpConnection.Connect(); string x = to.Replace(txtIP.Text, ""); if (x.StartsWith("/")) { x = x.Substring(1); } ftpConnection.ChangeWorkingDirectory(x); foreach (string f in files2) { if (bError) { return(false); } string fname = Path.GetFileName(f); try { ftpConnection.UploadFile(f, fname); } catch (Exception ex) { if (!bError) { bError = true; bCancel = true; MessageBox.Show(this, ex.Message + "\n" + fname + "\n\nDetails:\n" + ex.ToString(), "Failed to upload", MessageBoxButtons.OK, MessageBoxIcon.Error); } } progUpload.Value = (int)((1000 * UploadCount) / totalFiles); if (!bError) { UploadCount++; lbUploadPercent.Text = (progUpload.Value / 10).ToString() + "%" + " (" + UploadCount.ToString() + "/" + totalFiles.ToString() + ")"; Application.DoEvents(); } } ftpConnection.Close(); } catch (Exception ex) { } } //#else { try { string[] files2 = Directory.GetFiles(fromPath); foreach (string f in files2) { if (bError) { return(false); } string fname = Path.GetFileName(f); System.Threading.ThreadPool.QueueUserWorkItem(arg => { semConn.WaitOne(); using (MyWebClient webClient = new MyWebClient()) { webClient.Credentials = new NetworkCredential(uname, pwd); try { webClient.UploadFile("ftp://" + to + "/" + fname, f); while (webClient.IsBusy) { System.Threading.Thread.Sleep(100); } } catch (Exception ex) { lock (this) this.Invoke(new Action(() => { if (!bError) { bError = true; bCancel = true; MessageBox.Show(this, ex.Message + "\n" + fname + "\n\nDetails:\n" + ex.ToString(), "Failed to upload", MessageBoxButtons.OK, MessageBoxIcon.Error); } })); } this.Invoke(new Action(() => { progUpload.Value = (int)((1000 * UploadCount) / totalFiles); if (!bError) { UploadCount++; lbUploadPercent.Text = (progUpload.Value / 10).ToString() + "%" + " (" + UploadCount.ToString() + "/" + totalFiles.ToString() + ")"; Application.DoEvents(); } })); } semConn.Release(); }); } } catch (Exception ex) { } } return(true); #endif using (WebClient webClient = new WebClient()) { webClient.Credentials = new NetworkCredential(uname, pwd); string[] files2 = Directory.GetFiles(fromPath); foreach (string f in files2) { string fname = Path.GetFileName(f); try { webClient.UploadFile("ftp://" + to + "/" + fname, f); while (webClient.IsBusy) { System.Threading.Thread.Sleep(100); } } catch (Exception ex) { _lastError = ex.Message + "\n\n" + to + "/" + fname + "\n\nDetails:\n" + ex.ToString(); return(false); } try { //UploadState.Progress = UploadCount / totalFiles *100; } catch { } //Application.DoEvents(); UploadCount++; } } return(true); }
// 获取FTP递交信息 public Boolean QueryFTP() { log.WriteInfoLog("查询FTP目录信息..."); // 输出递交包,到本地集成环境处理,需要使用ftp连接 FTPConnection ftp = MAConf.instance.Configs[ProductId].ftp; FtpConf fc = MAConf.instance.Configs[ProductId].fc; string s; // 强制重新连接,防止时间长了就断掉了 if (ftp.IsConnected == false) { try { ftp.Connect(); } catch (Exception e) { log.WriteErrorLog("连接FTP服务器失败,错误信息:" + e.Message); return(false); } } // 取递交版本信息,确认要输出哪个版本的压缩包,确保只刷出最大的版本 // 这个地方,应该是如果存在集成的文件夹,就刷出集成的文件夹, // 对于V1,是全部都需要集成,对于Vn(n>1),只集成变动的部分就可以了 if (ftp.DirectoryExists(RemoteDir) == false) { System.Windows.Forms.MessageBox.Show("FTP路径" + RemoteDir + "不存在!"); return(false); } ftp.ChangeWorkingDirectory(fc.ServerDir); // 不使用 true 列举不出目录,只显示文件,很奇怪 //string[] files = ftp.GetFiles(fc.ServerDir + ap.CommitPath, true); string[] files = ftp.GetFiles(RemoteDir); log.WriteInfoLog("查询FTP目录信息...完成"); #region 确定修改单基本属性 // 检查是否存在集成*的文件夹 // 获取当前的版本信息,先标定版本信息 SubmitL.Clear(); ScmL.Clear(); ScmSrc.Clear(); foreach (string f in files) //查找子目录 { // 跳过 src-V*.rar 之类的东东 if (f.IndexOf("集成-src-V") >= 0 || f.IndexOf("集成-Src-V") >= 0) { ScmSrc.Add(f); } else if (f.IndexOf(MainNo) < 0) { continue; } else if (f.IndexOf("集成") == 0) { ScmL.Add(f); } else { SubmitL.Add(f); } } string currVerFile = string.Empty;// 20111123054-国金短信-李景杰-20120117-V3.rar if (SubmitL.Count > 0) { SubmitL.Sort(); s = SubmitL[SubmitL.Count - 1].ToString(); currVerFile = s; // 取递交版本号 // 20111207012-委托管理-高虎-20120116-V13.rar --> 20111207012-委托管理-高虎-20120116-V13 -> 13 s = s.Substring(0, s.LastIndexOf('.')); SubmitVer = int.Parse(s.Substring(s.LastIndexOf('V') + 1)); } else { SubmitVer = 0; } // 生成一些上次集成的变量,需要把上次的覆盖到本次来 if (ScmL.Count > 1) // 重复集成 { ScmL.Sort(); s = ScmL[ScmL.Count - 1].ToString(); // 取递交版本号 // 20111207012-委托管理-高虎-20120116-V13.rar --> 20111207012-委托管理-高虎-20120116-V13 -> 13 s = s.Substring(0, s.LastIndexOf('.')); ScmVer = int.Parse(s.Substring(s.LastIndexOf('V') + 1)); ScmedVer = ScmVer; // 如果存在对应的src文件夹,一并删除掉 if (ScmVer == SubmitVer) { ScmL.RemoveAt(ScmL.Count - 1); if (ScmSrc.Count > 1) { ScmSrc.Sort(); if (ScmSrc.IndexOf("集成-src-V" + ScmVer + ".rar") >= 0 || ScmSrc.IndexOf("集成-Src-V" + ScmVer + ".rar") >= 0) { ScmSrc.RemoveAt(ScmSrc.Count - 1); } } } } string dir = Path.GetFileNameWithoutExtension(currVerFile); //AmendDir = LocalDir + "\\" + dir; SCMAmendDir = Path.Combine(LocalDir, "集成-" + dir); ScmVer = SubmitVer; LocalFile = Path.Combine(LocalDir, currVerFile); RemoteFile = LocalFile.Replace(LocalDir, RemoteDir); SCMLocalFile = Path.Combine(SCMAmendDir, "集成-" + currVerFile); SCMRemoteFile = SCMLocalFile.Replace(SCMAmendDir, RemoteDir); SrcRar = Path.Combine(SCMAmendDir, "src-V" + ScmVer.ToString() + ".rar"); SCMSrcRar = Path.Combine(SCMAmendDir, "集成-src-V" + ScmVer.ToString() + ".rar"); SCMRemoteSrcRar = SCMSrcRar.Replace(SCMAmendDir, RemoteDir); if (ScmL.Count > 0) { ScmL.Sort(); s = ScmL[ScmL.Count - 1].ToString(); dir = Path.GetFileNameWithoutExtension(s); // 上次数据 SCMLastAmendDir = Path.Combine(LocalDir, dir); SCMLastLocalFile = Path.Combine(SCMLastAmendDir, s); ScmLastRemoteFile = Path.Combine(RemoteDir, s); // 取递交版本号 // 20111207012-委托管理-高虎-20120116-V13.rar --> 20111207012-委托管理-高虎-20120116-V13 -> 13 s = s.Substring(0, s.LastIndexOf('.')); SCMLastVer = int.Parse(s.Substring(s.LastIndexOf('V') + 1)); SCMLastLocalSrcRar = Path.Combine(SCMLastAmendDir, "集成-src-V" + SCMLastVer.ToString() + ".rar"); ScmLastRemoteSrcRar = Path.Combine(RemoteDir, "集成-src-V" + SCMLastVer.ToString() + ".rar"); } else { SCMLastVer = 0; } if (ScmedVer == 0) { ScmedVer = SCMLastVer; } if (ScmSrc.Count > 0) { ScmSrc.Sort(); s = ScmSrc[ScmSrc.Count - 1].ToString(); SCMLastLocalSrcRar = Path.Combine(SCMLastAmendDir, s); ScmLastRemoteSrcRar = Path.Combine(RemoteDir, s); } // 决定是新集成还是修复集成还是重新集成 if (ScmVer == 0 || (ScmVer == 1 && SubmitVer == 1)) // 第一次集成 { scmtype = ScmType.NewScm; } else if (SCMLastVer <= SubmitVer) // 重新集成也当成修复集成 { scmtype = ScmType.BugScm; // 修复集成 } #endregion return(true); }
public static void DeleteDirectory(string remotePath) { var ftpConnect = new FTPConnection(); try { ftpConnect.ServerAddress = System.Configuration.ConfigurationManager.AppSettings["HostGoDaddy"].ToString(); ftpConnect.ServerPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["PortGoDaddy"].ToString()); ftpConnect.UserName = System.Configuration.ConfigurationManager.AppSettings["UsernameGoDaddy"].ToString(); ftpConnect.Password = System.Configuration.ConfigurationManager.AppSettings["PasswordGoDaddy"].ToString(); ftpConnect.Connect(); //ftpConnect.Login(); //ftpConnect.Timeout = 1200000; ftpConnect.ChangeWorkingDirectory("/public_html/" + remotePath); var files = ftpConnect.GetFileInfos().Where(x => !x.Name.Contains(".")).OrderBy(x => x.LastModified); int index = 0; foreach (var f in files) { var dtLastModified = f.LastModified; int numberofDays = DateTime.Now.Subtract(dtLastModified).Days; if (numberofDays > 15) { index++; } } System.Windows.Forms.MessageBox.Show(index.ToString(), "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning); //foreach (var tmp in files) //{ // //var dtLastModified = tmp.LastModified; // //int numberofDays = DateTime.Now.Subtract(dtLastModified).Days; // //if (numberofDays > 15) // DeleteDirectoryRecursively(ftpConnect, tmp.Name); // //System.Threading.Thread.Sleep(2000); // break; // ; //} //files = ftpConnect.GetFileInfos().Where(x => !x.Name.Contains(".")).OrderBy(x => x.LastModified); //System.Windows.Forms.MessageBox.Show(files.Count().ToString(), "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning); } catch (Exception ex) { throw new Exception("Exception is " + ex.Message); } finally { ftpConnect.Close(); //ftpConnect.Dispose(); } }
/// <summary> /// Opens a connection to the FTP server and sends a file called Log.txt /// with the current date and time, to check that we can upload files. /// </summary> private void TestConnectionAndSendFile() { try { using (FTPConnection ftp = new FTPConnection()) { ftp.ServerAddress = Host; ftp.ServerPort = Port; ftp.UserName = Username; ftp.Password = Password; ftp.AutoPassiveIPSubstitution = PassiveMode; try { ftp.Connect(); } catch (Exception ex) { throw new FtpDownloadException("Unable to connect to server", ex); } try { if (!StringUtils.IsBlank(RemoteFolder)) { ftp.ChangeWorkingDirectory(RemoteFolder); } } catch (Exception ex) { throw new FtpDownloadException("Remote folder not found: " + RemoteFolder, ex); } // Message builder StringBuilder sb = new StringBuilder(); // Add date and user information sb.AppendFormat("Date: {0}\n", DateTime.Now.ToString("dd MMMM yyyy HH:mm:ss")); sb.AppendFormat("User: {0}\n", User.FullName); // Add ip address of requesting user (if known) if (HttpContext.Current != null) { sb.AppendFormat("Ip Address: {0}\n", HttpContext.Current.Request.UserHostAddress); } sb.AppendLine(); // Add file count sb.AppendFormat("File count: {0}", Files.Count); sb.AppendLine(); // Add filenames foreach (FtpFile file in Files) { sb.AppendFormat("- {0}, Remote Filename: {1}\n", Path.GetFileName(file.LocalPath), file.RemoteFilename); } sb.AppendLine(); sb.AppendLine("******************************"); sb.AppendLine(); sb.AppendLine(); sb.AppendLine(); try { // Upload the log UTF8Encoding encoding = new UTF8Encoding(); byte[] messageBytes = encoding.GetBytes(sb.ToString()); ftp.UploadByteArray(messageBytes, "Log.txt", false); } catch (Exception ex) { throw new FtpDownloadException("Unable to upload files: " + ex.Message, ex); } ftp.Close(); } } catch (Exception ex) { throw new FtpDownloadException(ex.Message, ex); } }
private void DoUpload() { try { using (FTPConnection ftp = new FTPConnection()) { ftp.ServerAddress = Host; ftp.ServerPort = Port; ftp.UserName = Username; ftp.Password = Password; ftp.AutoPassiveIPSubstitution = PassiveMode; ftp.ReplyReceived += new FTPMessageHandler(ServerResponse); ftp.Connect(); if (!StringUtils.IsBlank(RemoteFolder)) { ftp.ChangeWorkingDirectory(RemoteFolder); } int count = 0; foreach (FtpFile file in Files) { m_Logger.DebugFormat("Uploading {0} (file {1}/{2}) to {3} for {4}", file, count + 1, Files.Count, Host, User.FullName); if (StringUtils.IsBlank(file.LocalPath)) { m_Logger.Warn("File LocalPath is empty. Nothing to upload."); continue; } if (!File.Exists(file.LocalPath)) { m_Logger.WarnFormat("Asset File '{0}' does not exist. Nothing to upload.", file.LocalPath); continue; } m_Logger.DebugFormat("Uploading {0} to FTP server...", file.LocalPath); ftp.UploadFile(file.LocalPath, file.RemoteFilename); m_Logger.Debug("...Done"); count++; } ftp.Close(); m_Logger.DebugFormat("Uploaded {0} files to {1} for {2}", count, Host, User.FullName); } if (UploadComplete != null) { FtpDownloadCompleteEventArgs e = new FtpDownloadCompleteEventArgs { ServerMessages = m_ServerResponses.ToString(), User = User }; UploadComplete(this, e); } } catch (Exception ex) { // Initialise error message StringBuilder sb = new StringBuilder(); sb.AppendLine("An error occured when doing an FTP transfer"); // Add the error message sb.AppendLine(ex.ToString()); sb.AppendLine(); // Add the server messages sb.Append(m_ServerResponses.ToString()); sb.AppendLine(); string message = sb.ToString(); m_Logger.Error(message, ex); } }