Example #1
0
        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
            {
            }
        }
Example #2
0
 //hack[Test]
 public void FTPS()
 {
     try
     {
         var settings = new FTPConnection.SettingsData
         {
             RemoteHost = "192.168.0.150",
             RemotePort = 21,
             UserName   = "******",
             Password   = "******",
             UseSSL     = false
         };
         using (var ftp = new FTPConnection())
         {
             ftp.TraceMessage += (s, a) => { System.Diagnostics.Debug.Write(string.Format(s, a)); };
             ftp.Login(settings);
             ftp.AsciiMode = true;
             ftp.Upload(@"D:\deleteme\test.html");
             ftp.Close();
         }
     }
     catch (Exception e)
     {
         System.Diagnostics.Debug.WriteLine("Caught Error :" + e.Message);
     }
 }
Example #3
0
 public void CloseFTP()
 {
     try
     {
         myFTP.Close();
     }
     catch (FTPException)
     {
         //Debug.WriteLine("FTPException: No Connection to Close");
         throw new Exception("No Connection to Close!");
     }
     catch (ControlChannelIOException)
     {
         //Debug.WriteLine("ControlChannelIOException: Connection Already Aborted by Server");
         throw new Exception("Connection already aborted by server!");
     }
 }
Example #4
0
        /// <summary>
        /// 断开连接
        /// </summary>
        public void Disconnect()
        {
            if (m_pFtp != null && m_pFtp.IsConnected)
            {
                Cancel();

                try
                {
                    m_pFtp.Close();
                }
                catch { }
            }
        }
Example #5
0
        [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();
        }
Example #6
0
        /// <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();
            }
        }
Example #7
0
        /// <summary>
        /// File via FTP öffnen
        /// </summary>
        /// <returns></returns>
        private void logViaFTPÖffnenToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TextBox.Clear();
            IniFile lIni = new IniFile();

            if (lIni.Read("LOG", "Receiver") == "")
            {
                return;
            }
            string ftpUri      = lIni.Read("IP", "Receiver");
            string ftpUser     = lIni.Read("USER", "Receiver");;
            string passwd      = lIni.Read("PWD", "Receiver");
            string ftpfileName = Path.GetFileName(lIni.Read("LOG", "Receiver"));
            string ftpfilePath = lIni.Read("LOG", "Receiver");

            ftpfilePath = ftpfilePath.Remove(Math.Max(0, ftpfilePath.Length - ftpfileName.Length - 1), ftpfileName.Length + 1);

            FTPConnection ftpCon        = new FTPConnection();
            string        localFileName = Path.GetTempFileName();
            //Prgressbar aufbauen
            ProgressForm lProgress = new ProgressForm();

            lProgress.StartPosition = FormStartPosition.CenterParent;
            lProgress.Show(this);
            lProgress.SetProgress("Öffne FTP Verbindung", 0);
            //FTP verbinden
            ftpCon.Open(ftpUri, ftpUser, passwd, FTPMode.Passive);
            lProgress.SetProgress("Wechsle Verzeichnis", 20);
            ftpCon.SetCurrentDirectory(ftpfilePath);
            lProgress.SetProgress("Lade Daten", 40);
            ftpCon.GetFile(ftpfileName, localFileName, FTPFileTransferType.Binary);
            lProgress.SetProgress("Schließe Verbindung", 60);
            ftpCon.Close();
            lProgress.SetProgress("Lese Datei", 80);
            readFile(localFileName);
            //Ende
            lProgress.SetProgress("Fertig ...", 100);
            lProgress.Close();
            CountLines();

            DetectCamType();
            ReadLengthInfo(vCamType);
        }
Example #8
0
        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();
            }
        }
Example #9
0
        public bool Process(Queue.QueueItem item)
        {
            string    ftpHost = Settings.Default.FtpHost;
            Semaphore lockOne;

            lock (_syncRoot)
            {
                if (!_connLocks.ContainsKey(ftpHost))
                {
                    int semaphorePoolSize = Settings.Default.ConcurentFTPConnectionsCount;
                    lockOne = new Semaphore(0, semaphorePoolSize);
                    lockOne.Release(semaphorePoolSize);
                    _connLocks.Add(ftpHost, lockOne);
                }
                else
                {
                    lockOne = _connLocks[ftpHost];
                }
            }
            lockOne.WaitOne();
            try
            {
                bool          result = false;
                FTPConnection conn   = new FTPConnection();
                conn.Open(Settings.Default.FtpHost, Settings.Default.FtpUserName, Settings.Default.FtpPassword, FTPMode.Passive);
                conn.SetCurrentDirectory(Settings.Default.FtpTargetFolder);
                conn.SendFile(item.FileFullPath, FTPFileTransferType.Binary);
                conn.Close();
                result = true;
                return(result);
            }
            finally
            {
                lockOne.Release();
            }
        }
Example #10
0
        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);
        }
Example #11
0
    //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);
        }
    }
Example #12
0
        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();
            }
        }
Example #13
0
        /// <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);
            }
        }
Example #14
0
        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);
            }
        }
Example #15
0
        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();
        }