/// <summary> /// 连接FTP服务器 /// </summary> /// <param name="ftpInfo"></param> /// <returns></returns> public static bool ConnectFtpServer(FtpConfigEntity ftpInfo) { try { using (FTPConnection ftpConn = new FTPConnection { ServerAddress = ftpInfo.ServerAddress, //ServerDirectory = ftpInfo.ServerDirectory, UserName = ftpInfo.UserName, Password = ftpInfo.UserPassword, CommandEncoding = Encoding.GetEncoding("GBK") }) { ftpConn.Connect(); if (!ftpConn.DirectoryExists(ftpInfo.ServerDirectory)) { throw new Exception($"FTP服务器连接成功,但FTP服务器不存在目录名[{ftpInfo.ServerDirectory}]"); } } return(true); } catch (Exception ex) { string errMsg = $"FTP服务器连接失败,FTP信息[{JsonObj<FtpConfigEntity>.ToJson(ftpInfo)}],异常[{ ex.Message}]"; LogUtil.WriteLog(errMsg); throw new Exception(errMsg); } }
public Boolean DeletePack(int v) { // 输出递交包,到本地集成环境处理,需要使用ftp连接 FTPConnection ftp = MAConf.instance.Configs[ProductId].ftp; FtpConf fc = MAConf.instance.Configs[ProductId].fc; // 强制重新连接,防止时间长了就断掉了 if (ftp.IsConnected == false) { try { ftp.Connect(); } catch (Exception e) { log.WriteErrorLog("连接FTP服务器失败,错误信息:" + e.Message); } } if (ftp.DirectoryExists(RemoteDir) == false) { System.Windows.Forms.MessageBox.Show("FTP路径" + RemoteDir + "不存在!"); return(false); } //ftp.ChangeWorkingDirectory(fc.ServerDir); ftp.DeleteFile(RemoteFile); return(true); }
public void Connect(string host, int port, string user, string password, string serverDirectory) { try { if (host.Trim() == "") { UtilException ex = new UtilException("Host is empty.", Exception_ExceptionSeverity.High); throw ex; } ftp.ServerAddress = host.Trim(); ftp.ServerPort = port; ftp.UserName = user.Trim(); ftp.Password = password; ftp.ServerDirectory = serverDirectory; ftp.Connect(); } catch (Exception ex) { if (ftp.IsConnected) { ftp.Close(); } throw ex; } finally { } }
/// <summary> /// 执行一个ftp操作 /// </summary> /// <param name="action"></param> /// <param name="exceptionHandler"></param> public void SafeAction(Action <FTPConnection> action, Action <Exception> exceptionHandler = null) { try { using (FTPConnection connection = new FTPConnection()) { connection.ServerAddress = _serverIp; connection.UserName = _userName; connection.Password = _password; connection.ServerPort = _serverPort; //默认使用的就是PASV被动模式 connection.ConnectMode = FTPConnectMode.PASV; //设置传输类型Binary,默认就是Binary connection.TransferType = FTPTransferType.BINARY; //不用设置命令编码,采用默认值,注意传输文件名使用ASCII值 //只使用0-127的文件名不会出错。 connection.Timeout = 6000;//单位毫秒 connection.Connect(); if (action != null) { action(connection); } } } catch (Exception ex) { if (exceptionHandler != null) { exceptionHandler(ex); } } }
public bool ConnectFTP() { bool bRet = false; try { myFTP.Connect(); bRet = true; } catch (FTPAuthenticationException) { //NOTE: If connected, but wrong login information, client will //be automatically disconnected. //Debug.WriteLine("AuthExeption: Invalid Username/Password"); CloseFTP(); throw new Exception("Invalid Username/Password!"); } catch (IOException) { //Could be invalid server IP or port number, or server offline //Debug.WriteLine("IOException: Failed to Connect"); throw new Exception("Unable to connect!"); } catch (ArgumentNullException) { //Client may still connect if there is empty field. //Debug.WriteLine("NullException: Empty Field"); CloseFTP(); throw new Exception("Empty Field!"); } catch (System.Net.Sockets.SocketException) { //Debug.WriteLine("SocketException: No Response from Server"); throw new Exception("No response from server!"); } catch (FTPException) { //Debug.WriteLine("FTPException: Already Connected 2"); throw new Exception("Unknown FTPException!"); } return(bRet); }
public void RunTestOutsideHarness(bool useAbsPaths) { Init(); ftp = new FTPConnection(); ftp.ServerAddress = "localhost"; ftp.UserName = "******"; ftp.Password = "******"; PrepareConnection(); ftp.Connect(); RunTests(useAbsPaths); }
/// <summary> /// 上传文件 /// </summary> /// <param name="ftpInfo"></param> /// <param name="sourceFilepath"></param> public static void UploadFile(FtpConfigEntity ftpInfo, string sourceFilepath) { if (ftpInfo == null) { throw new Exception("FtpHelper.UploadFile()方法,参数ftpInfo为空"); } if (string.IsNullOrEmpty(sourceFilepath)) { throw new Exception("FtpHelper.UploadFile()方法,参数sourceFilepath为空"); } if (!File.Exists(sourceFilepath)) { throw new Exception($"FtpHelper.UploadFile()方法,参数sourceFilepath[{sourceFilepath}]指定文件路径不存在"); } try { using (FTPConnection ftpConn = new FTPConnection { ServerAddress = ftpInfo.ServerAddress, ServerDirectory = ftpInfo.ServerDirectory, UserName = ftpInfo.UserName, Password = ftpInfo.UserPassword, CommandEncoding = Encoding.GetEncoding("GB2312") }) { ftpConn.Connect(); string tempFtpFileName = FileHelper.GetFileName(sourceFilepath) + ".part"; string ftpFileName = FileHelper.GetFileName(sourceFilepath); bool exist_file = ftpConn.Exists(tempFtpFileName); if (exist_file) { LogUtil.WriteLog($"FTP服务器存在同名文件[{tempFtpFileName}],将ResumeNextTransfer"); ftpConn.ResumeNextTransfer(); } ftpConn.UploadFile(sourceFilepath, tempFtpFileName, exist_file); Thread.Sleep(200); ftpConn.RenameFile(tempFtpFileName, ftpFileName); } } catch (Exception ex) { throw new Exception($"数据文件[{sourceFilepath}]上传失败,异常信息[{ex.Message}][{ex.StackTrace}]"); } }
[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(); }
/// <summary> Connect to the server </summary> internal void Connect(int timeout, bool autoLogin) { // connect ftp = new FTPConnection(); ftp.AutoLogin = autoLogin; ftp.ServerAddress = host; ftp.ServerPort = FTPControlSocket.CONTROL_PORT; ftp.Timeout = timeout; ftp.ConnectMode = connectMode; ftp.UserName = user; ftp.Password = password; log.Debug("Connecting to " + host); ftp.Connect(); log.Debug("Connected to " + host); }
private void Connect() { if (connection != null && connection.IsConnected) { return; } connection = new FTPConnection(); connection.Timeout = Timeout; connection.ServerAddress = account.Url; connection.UserName = account.UserName; connection.Password = account.Password; connection.Connect(); }
static void Main(string[] args) { using (var connection = new FTPConnection { ServerAddress = "127.0.0.1", UserName = "******", Password = "******", }) { connection.Connect(); connection.ServerDirectory = "/recursive_folder"; var resultRecursive = connection.GetFileInfosRecursive().Where(f => !(f.Name.EndsWith(".old"))).ToList(); var resultDefault = connection.GetFileInfos().Where(f => !(f.Name.EndsWith(".old"))).ToList(); } }
/// <summary> /// /// </summary> /// <param name="ip"></param> public void testServer(string ip) { FTPConnection ftp = new FTPConnection(); string current = "setup"; try { Console.Out.WriteLine("Testing: " + ip); ftp.ServerAddress = ip; ftp.UserName = "******"; ftp.Password = "******"; ftp.Timeout = 5000; current = "connecting"; ftp.Connect(); current = "uploading"; ftp.UploadFile("test.txt", "test.txt"); current = "testing"; if (ftp.Exists("test.txt")) { current = "deleting"; ftp.DeleteFile("test.txt"); Console.WriteLine("OK: " + ip, Color.Lime); okservers++; goodServers.Add(ip); using (StreamWriter w = File.AppendText(outputFile)) { w.WriteLine(ip); } } else { throw new Exception("File could not be uploaded" + ip); } ftp.DeleteFile("test.txt"); } catch (Exception ex) { Console.WriteLine("Error: " + current + " " + ex.Message); } finally { current = "closing"; ftp.Close(); } }
/// <summary> /// 连接 FTP 服务器 /// </summary> /// <returns></returns> public bool Connect() { this.FileSize = 0; this.TransferredSize = 0; this.TargetOriginalFileSize = 0; TransferEventArgs arg = new TransferEventArgs(); if (OnTransfering != null) { arg.TransferStatus = Status.Connecting; arg.FileSize = 0; arg.TransferredSize = 0; arg.Exception = null; OnTransfering(this.m_pFtp, arg); } try { m_pFtp.Connect(); } catch (Exception e) { if (OnTransfering != null) { arg.TransferStatus = Status.Failed; arg.FileSize = 0; arg.TransferredSize = 0; arg.Exception = e; OnTransfering(this.m_pFtp, arg); } else { throw e; } } return(m_pFtp.IsConnected); }
/// <summary> /// 连接FTP服务器 /// </summary> /// <param name="ftpInfo"></param> /// <returns></returns> public static bool ConnectFtpServer(FtpInfoEntity ftpInfo) { try { using (FTPConnection ftpConn = new FTPConnection { ServerAddress = ftpInfo.ServerAddress, ServerDirectory = ftpInfo.ServerDirectory, UserName = ftpInfo.UserName, Password = ftpInfo.UserPassword, CommandEncoding = Encoding.GetEncoding("GBK") }) { ftpConn.Connect(); } return(true); } catch (Exception ex) { LogUtil.WriteLog($"FTP服务器连接失败,FTP信息[{JsonObj<FtpInfoEntity>.ToJson(ftpInfo)}],异常[{ ex.Message}]"); return(false); } }
/// <summary> /// 上传文件 /// </summary> /// <param name="ftpInfo"></param> /// <param name="t8FileInfo"></param> public static void UploadFile(FtpInfoEntity ftpInfo, T8FileInfoEntity t8FileInfo) { using (FTPConnection ftpConn = new FTPConnection { ServerAddress = ftpInfo.ServerAddress, ServerDirectory = ftpInfo.ServerDirectory, UserName = ftpInfo.UserName, Password = ftpInfo.UserPassword, CommandEncoding = Encoding.GetEncoding("GBK") }) { ftpConn.Connect(); bool exist_file = ftpConn.Exists(t8FileInfo.FileName); if (exist_file) { LogUtil.WriteLog($"FTP服务器存在同名文件[{t8FileInfo.FileName}],将ResumeNextTransfer"); ftpConn.ResumeNextTransfer(); } ftpConn.UploadFile(t8FileInfo.FilePath, t8FileInfo.FileName, exist_file); } }
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); }
static void Main(string[] args) { Local_long_listFiles = new List <string>(); Local_Short_listFiles = new List <string>(); string dirName = ConfigurationManager.AppSettings["dirName"]; if (Directory.Exists(dirName)) { Console.WriteLine("Подкаталоги:"); string[] dirs_ = Directory.GetDirectories(dirName); for (int i = 0; i < dirs_.Length; i++) { Local_long_listFiles.Add(dirs_[i]); dirs_[i] = new FileInfo(dirs_[i]).Name; // Выделяем короткое название из пути Local_Short_listFiles.Add(dirs_[i]); Console.WriteLine(Local_long_listFiles[i]); Console.WriteLine(Local_Short_listFiles[i]); /* string[] files = Directory.GetFiles(s); * foreach (string p in files) * { * Console.WriteLine(p); * }*/ } } FTPConnection ftp = new FTPConnection(); ftp.ConnectMode = FTPConnectMode.ACTIVE; ftp.ServerAddress = ConfigurationManager.AppSettings["ServerAddress"]; ftp.UserName = ConfigurationManager.AppSettings["UserName"]; ftp.Password = ConfigurationManager.AppSettings["UserName"]; ftp.Connect(); FTPFile[] filesFTP = ftp.GetFileInfos(); if (filesFTP.Length > 0) { //int a = 0; for (int i = 0; i < Local_Short_listFiles.Count; i++) { //Console.WriteLine(filesFTP[i].Name); for (int k = 0; k < filesFTP.Length; k++) { if (filesFTP[k].Name == Local_Short_listFiles[i]) { break; } if (k == filesFTP.Length - 1) { try { ftp.CreateDirectory(Local_Short_listFiles[i]); main_Long_files = Directory.GetFiles(Local_long_listFiles[i]); main_Short_files = Directory.GetFiles(Local_long_listFiles[i]); for (int s = 0; s < main_Short_files.Length; s++) { main_Short_files[s] = new FileInfo(main_Short_files[s]).Name; ftp.UploadFile(main_Long_files[s], ($"/{Local_Short_listFiles[i]}/{main_Short_files[s]}"), true); } } catch (Exception a) { Console.WriteLine("Ошибка при создании папки и копировании файлов"); } } } // удаляем каталог после записи try { DirectoryInfo dirInfo = new DirectoryInfo(Local_long_listFiles[i]); dirInfo.Delete(true); Console.WriteLine("Каталог удален"); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } else { for (int i = 0; i < Local_Short_listFiles.Count; i++) { try { ftp.CreateDirectory(Local_Short_listFiles[i]); main_Long_files = Directory.GetFiles(Local_long_listFiles[i]); main_Short_files = Directory.GetFiles(Local_long_listFiles[i]); for (int s = 0; s < main_Short_files.Length; s++) { main_Short_files[s] = new FileInfo(main_Short_files[s]).Name; ftp.UploadFile(main_Long_files[s], ($"/{Local_Short_listFiles[i]}/{main_Short_files[s]}"), true); } } catch (Exception a) { Console.WriteLine("Ошибка при создании папки и копировании файлов"); } // удаляем каталог после записи try { DirectoryInfo dirInfo = new DirectoryInfo(Local_long_listFiles[i]); dirInfo.Delete(true); Console.WriteLine("Каталог удален"); } catch (Exception ex) { Console.WriteLine(ex.Message); } } } //ftp.CreateDirectory("testDir"); //ftp.UploadFile("C:/VisualStudioProject/TestFTP/NET/TestFTP/TestFTP/bin/Debug/test.txt", "/testDir/test.txt", true); //ftp.DownloadFile("test.txt", "testDir/test.txt"); /*string[] fileDetails = ftp.GetFiles(); * foreach (string a in fileDetails) * { * Console.WriteLine(a); * if (a == "./testDir") * { * Console.WriteLine("папка testDir"); * } * }*/ FTPFile[] filesFTP_ = ftp.GetFileInfos(); foreach (FTPFile d in filesFTP_) { Console.WriteLine(); Console.WriteLine(d + "информация о файле"); Console.WriteLine(); Console.WriteLine(d.Dir + " - Dir"); Console.WriteLine(d.Group + " - Group"); Console.WriteLine(d.LastModified + " - LastModified"); Console.WriteLine(d.Link + " - Link"); Console.WriteLine(d.LinkCount + " - LinkCount"); Console.WriteLine(d.LinkedName + " - LinkedName"); Console.WriteLine(d.Name + " - Name"); Console.WriteLine(d.Owner + " - Owner"); Console.WriteLine(d.Permissions + " - Permissions"); Console.WriteLine(d.Raw + " - Raw"); Console.WriteLine(d.Size + " - Size"); Console.WriteLine(d.Type + " - Type"); Console.WriteLine(); /*if (d.Name == "testDir") * { * Console.WriteLine("папка testDir"); * ftp.ChangeWorkingDirectory(d.Name); // сменить рабочую директорию * //foreach() * FTPFile[] files__FTP = ftp.GetFileInfos(); * foreach (FTPFile g in files__FTP) * { * Console.WriteLine(g); * } * * }*/ } // сортировка директории по дате создания (первая самая новая) FTPFile temp; for (int i = 0; i < filesFTP_.Length - 1; i++) { for (int j = i + 1; j < filesFTP_.Length; j++) { if (filesFTP_[i].LastModified < filesFTP_[j].LastModified) { temp = filesFTP_[i]; filesFTP_[i] = filesFTP_[j]; filesFTP_[j] = temp; } } } Console.WriteLine("После сортировки"); foreach (FTPFile a in filesFTP_) { Console.WriteLine(a.Name); } /*if (filesFTP_.Length > 1) * { * for (int i = 1; i < filesFTP_.Length; i++) * { * Console.WriteLine(filesFTP_[i].Name); * ftp.ChangeWorkingDirectory(filesFTP_[i].Name); // сменить рабочую директорию * FTPFile[] files__FTP = ftp.GetFileInfos(); * foreach (FTPFile g in files__FTP) * { * ftp.DeleteFile(g.Name); * } * Console.WriteLine("Файлы удалены из директории"); * ftp.ChangeWorkingDirectoryUp(); * ftp.DeleteDirectory(filesFTP_[i].Name); * Console.WriteLine("Старые директории удалены"); * * } * }*/ // Список локальных директорий /*string[] dirs = Directory.GetDirectories(@"D:\\APP", "*", SearchOption.TopDirectoryOnly); * for (int i = 0; i < dirs.Length; i++) * { * dirs[i] = new FileInfo(dirs[i]).Name; // Выделяем короткое название из пути * } * * // Список удаленных директорий * FTPFile[] file__Details = ftp.GetFileInfos(""); * foreach (FTPFile file in file__Details) * { * if (file.Dir && Array.Exists(dirs, x => x == file.Name)) * { * Console.WriteLine(file.Name + " " + file.Dir); * } * * //Console.WriteLine(file.Name + " " + file.Dir); * }*/ ftp.Close(); Console.Read(); }
protected void btn_filtros_Click(object sender, EventArgs e) { String _Div = ""; DataSet _Salas = fs._Get_Visitas_por_sala(cbo_auditor.SelectedValue, txt_fecha.Text); if (_Salas != null) { if (_Salas.Tables[0].Rows.Count > 0) { int _Total_Salas = 0; FTPConnection _Ftp = new FTPConnection(); _Ftp.UserName = "******"; _Ftp.Password = "******"; _Ftp.ServerAddress = "200.29.139.242"; _Ftp.ServerPort = 21; _Ftp.ServerDirectory = "BBDD_SUPI/FOTOS_SALA/" + txt_fecha.Text + "/"; _Ftp.ConnectMode = FTPConnectMode.PASV; _Ftp.Timeout = 5000; _Ftp.TransferType = FTPTransferType.BINARY; _Ftp.Connect(); _Ftp.Timeout = 10000; foreach (DataRow dataRow in _Salas.Tables[0].Rows) { Boolean _Agrega = true; int _Eentra = 0; String _Llave = dataRow[0].ToString() + "_" + dataRow[1].ToString(); //String _Nombre_Auditor = dataRow[3].ToString(); ; String _Fecha = dataRow[1].ToString();; foreach (String _File in _Ftp.GetFiles(_Llave + "/*.jpg")) { String _Tamano = _Ftp.GetSize(_File).ToString(); if (_Tamano != "0") { _Eentra = 1; if (_Agrega) { _Total_Salas++; _Agrega = false; _Div = _Div + "<div class=\"titulo\">" + dataRow[0].ToString() + " " + dataRow[2].ToString() + "</div> "; _Div = _Div + "<div class=\"glihtbox\">"; _Div = _Div + "<ul class=\"list-unstyled row\" style=\"margin-bottom: 15px; margin-top: 5px;padding-left:0px;\">"; _Div = _Div + "<li style=\"padding-right:10px;\">"; } else { _Div = _Div + "<li style=\"padding-right:10px;\">"; } _Div = _Div + "<a href=\"" + "http://200.29.139.242/BBDD_SUPI/FOTOS_SALA/" + txt_fecha.Text + "/" + _File + "\" data-sub-html=\"<h4>" + dataRow[1].ToString() + " " + dataRow[0].ToString() + "</h4>\">"; _Div = _Div + "<img class=\"img-responsive\" src=\"" + "http://200.29.139.242/BBDD_SUPI/FOTOS_SALA/" + txt_fecha.Text + "/" + _File + "\" width=100 height=100 />"; _Div = _Div + "</a>"; _Div = _Div + "</li>"; } } if (_Eentra == 1) { _Div = _Div + "</ul></div>"; _Eentra = 0; } //_Div = _Div + "</ul>"; } } } _Div = _Div + "</ul></div>"; galleryHTML.InnerHtml = _Div; }
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); } }
// 获取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); }
//Muestra fotos en modo edicion... public void _Modo_Edicion(String _Medicion) { btn_eliminafoto.Visible = true; //********** LOGS BUSQUEDA POR MEDICION *********** String _Nombre_Calendario = _F._Get_Nombre_Calendario(cbo_medicion.SelectedValue); String _Id_Estudio = _F._Get_Id_Estudio(cbo_medicion.SelectedValue); try { String _Id_Pagina = _U._Get_Id_Pagina(Request.Url.Segments[Request.Url.Segments.Length - 1]); _G._Set_Insert_Logs(Session["Id_Usuario"].ToString(), DateTime.Now.ToString("yyyy-MM-dd H:mm:ss"), "BUSQUEDA FOTOS MODO EDICION", _Id_Pagina, _Id_Estudio, ""); } catch (Exception) { } DataSet _Ds_Salas = _F._Get_Listado_Fotos(_Medicion, ""); if (_Ds_Salas != null) { try { _Parametros(); _Ftp.Connect(); } catch (Exception) { ClientScript.RegisterStartupScript(this.GetType(), "Acceso", "swal('Error FTP', 'No se puede conectar con el servidor FTP', 'error');", true); return; } if (_Ds_Salas.Tables[0].Rows.Count > 0) { dgw_fotos.Visible = true; DataTable dt = new DataTable(); dt.Columns.Add("cc", typeof(Boolean)); dt.Columns.Add("Auditor", typeof(string)); dt.Columns.Add("Faculty", typeof(string)); dt.Columns.Add("Fecha", typeof(string)); dt.Columns.Add("Ruta", typeof(string)); dt.Columns.Add("imageurl", typeof(string)); foreach (DataRow dataRow in _Ds_Salas.Tables[0].Rows) { try { foreach (String _File in _Ftp.GetFiles(dataRow[1].ToString() + "/*.jpg")) { String _Tamano = _Ftp.GetSize(_File).ToString(); if (_Tamano != "0") { int B = _File.IndexOf("NO_VALIDA"); if (B > 0) { dt.Rows.Add(true, dataRow[4].ToString(), dataRow[0].ToString(), dataRow[3].ToString(), "http://200.29.139.242/BBDD_SUPI/" + _File, "http://200.29.139.242/BBDD_SUPI/" + _File); } else { dt.Rows.Add(false, dataRow[4].ToString(), dataRow[0].ToString(), dataRow[3].ToString(), "http://200.29.139.242/BBDD_SUPI/" + _File, "http://200.29.139.242/BBDD_SUPI/" + _File); } } } } catch (Exception) { ClientScript.RegisterStartupScript(this.GetType(), "Acceso", "swal('ERROR', 'NO SE PUEDEN MOSTRAR LAS FOTOS', 'error');", true); return; } } galleryHTML.InnerHtml = ""; dgw_fotos.DataSource = dt; dgw_fotos.DataBind(); _Ftp.Close(); } } else { ClientScript.RegisterStartupScript(this.GetType(), "Acceso", "swal('SIN FOTOS', 'NO SE HAN ENCONTRADO FOTOS PARA MEDICION SELECCIONADA', 'error');", true); } }
/// <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); } }
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(); } }