Beispiel #1
0
        private bool _Reconnect()
        {
            try
            {
                if (_ftpSession != null)
                {
                    _ftpSession.Close();
                    _ftpSession.Dispose();
                    _ftpSession = null;
                    GC.Collect();
                }

                _ftpSession = new FtpConnection(_host, _port, _user, _pass);
                _ftpSession.Open();
                _ftpSession.Login();
                GatLogger.Instance.AddMessage("Ftp Session {0} connected successfully");
                return(true);
            }
            catch (Exception e)
            {
                if (_ftpSession != null)
                {
                    _ftpSession.Close();
                    _ftpSession.Dispose();
                    _ftpSession = null;
                    GC.Collect();
                }
            }

            return(false);
        }
Beispiel #2
0
        static void Main(string[] args)
        {
            try
            {
                string strSource      = "D:\\Syed\\" + "Sample.txt";
                string ftpusername    = "******";
                string ftppassword    = "******";
                string ip             = "172.26.50.199";//provide ur ftp server ip address
                int    FtpPort        = Convert.ToInt16(21);
                string RemoteFileName = "Notifications\\sample.txt";
                using (FtpConnection _ftp = new FtpConnection(ip, FtpPort, ftpusername, ftppassword))
                {
                    try
                    {
                        string str = Path.GetFullPath("D:\\Syed\\sample.txt");
                        _ftp.Open();
                        _ftp.Login();
                        _ftp.PutFile(strSource, RemoteFileName);
                    }
                    catch (FtpException ex)
                    {
                        throw ex;
                    }
                }
                Program obj = new Program();
                obj.GetFile();
            }

            catch (System.Exception ex)
            {
                throw ex;
            }
        }
        private void buttonPublishBulletin_Click(object sender, EventArgs e)
        {
            var source              = openFileDialog2.FileName;
            var fileName            = openFileDialog2.SafeFileName;
            var destinationFileName = txtCaption.Text == String.Empty ? fileName : txtCaption.Text.Replace(" ", "_") +
                                      fileName.Substring(fileName.LastIndexOf("."));

            var destinationFolder = getBulletinsPagePath();

            var destination = String.Format("{0}/{1}", destinationFolder, destinationFileName);

            using (var ftp = new FtpConnection(m_ftpSite, m_ftpUsername, m_ftpPassword))
            {
                try
                {
                    ftp.Open();
                    ftp.Login();

                    if (!ftp.DirectoryExists(destinationFolder))
                    {
                        MessageBox.Show(
                            "The destination folder doesn't exist on the server. Please contact the BFI website administrator.");
                    }

                    ftp.PutFile(source, destination);
                    MessageBox.Show("Published bulletin successfully");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }
 private void Connect(Credentials credentials)
 {
     //Create the ftp connection
     _Connection = new FtpConnection(credentials.Host, credentials.Username, credentials.Password);
     _Connection.Open();
     _Connection.Login();
 }
Beispiel #5
0
        public static List <string> GetFileList(string ftpServerName, int ftpPortNumber, string ftpServerUserName, string ftpServerPassWord, string folder, DateTime ReadDate)
        {
            var results = new List <string>();

            // New FTp client to get modify date
            string        ftpServerNameNewClient = ftpServerName.Split('/').Last();
            FtpConnection ftp = new FtpConnection(ftpServerNameNewClient, ftpPortNumber, ftpServerUserName, ftpServerPassWord);

            ftp.Open();
            ftp.Login();

            var files = new FtpFileInfo[0];

            if (folder != "")
            {
                ftp.SetCurrentDirectory(folder);
            }

            files = ftp.GetFiles();

            foreach (var file in files)
            {
                DateTime?lastWriteTime = file.LastWriteTime;

                if (lastWriteTime != null && lastWriteTime >= ReadDate)
                {
                    results.Add(file.Name);
                }
            }

            ftp.Close();
            return(results);
        }
Beispiel #6
0
        private void DownloadDirectories(FtpConnection ftp, FtpDirectoryInfo[] dic, string remotePath, string localPath)
        {
            foreach (var ftpDirectoryInfo in dic.Where(d => d.Name != "." && d.Name != ".."))
            {
                if (_activeConnections < MaxActiveConnections)
                {
                    _activeConnections++;

                    _downloadTasks.Add(Task.Run(() =>
                    {
                        using (FtpConnection ftp2 = GetNewConnection())
                        {
                            ftp2.Open();
                            ftp2.Login();

                            ftp2.SetCurrentDirectory(remotePath + "/" + ftpDirectoryInfo.Name);

                            DownloadFiles(ftp2, ftp2.GetFiles(), remotePath + "/" + ftpDirectoryInfo.Name, Path.Combine(localPath, ftpDirectoryInfo.Name));
                            DownloadDirectories(ftp2, ftp2.GetDirectories(), remotePath + "/" + ftpDirectoryInfo.Name, Path.Combine(localPath, ftpDirectoryInfo.Name));
                        }
                    }));
                }
                else
                {
                    ftp.SetCurrentDirectory(remotePath + "/" + ftpDirectoryInfo.Name);
                    DownloadFiles(ftp, ftp.GetFiles(), remotePath + "/" + ftpDirectoryInfo.Name, Path.Combine(localPath, ftpDirectoryInfo.Name));
                    DownloadDirectories(ftp, ftp.GetDirectories(), remotePath + "/" + ftpDirectoryInfo.Name, Path.Combine(localPath, ftpDirectoryInfo.Name));
                }
            }
        }
    public void Connect(FTPCredentials credentials, Process process, SupplierSettingClass settings)
    {
        var ftp = new FtpConnection(credentials.Host, credentials.Username, credentials.Password);

        ftp.Open();
        ftp.Login();
        DoSomething(settings);
        ftp.Close();
    }
Beispiel #8
0
        private void SendAddOnToServer(List <string> files, String folderPath)
        {
            Console.WriteLine("Sending to server");
            TextReader tr   = new StreamReader(@"C:\Users\Pilus\Documents\Cloud Backup\PrologueServer.txt");
            string     addr = tr.ReadLine();
            string     user = tr.ReadLine();
            string     pass = tr.ReadLine();


            using (FtpConnection ftp = new FtpConnection(addr, user, pass)) {
                ftp.Open();  /* Open the FTP connection */
                ftp.Login(); /* Login using previously provided credentials */

                int c          = 0;
                int c2         = 0;
                int transfered = 0;

                foreach (String file in files)
                {
                    try {
                        // Check if the directory exists
                        String relativeFilePath = file.Replace(folderPath, "").Replace(@"\", "/");
                        String totalDirPath     = relativeFilePath.Substring(0, relativeFilePath.LastIndexOf("/"));
                        String folder           = totalDirPath.Substring(totalDirPath.LastIndexOf("/") + 1);
                        String topDir           = "/" + totalDirPath.Replace("/" + folder, "");
                        if (!ftp.GetCurrentDirectory().Equals("/" + totalDirPath))
                        {
                            ftp.SetCurrentDirectory(topDir);
                            if (!ftp.DirectoryExists(folder))
                            {
                                ftp.CreateDirectory(folder);
                            }
                        }



                        if (PutFile(ftp, file) == true)
                        {
                            transfered++;
                        }

                        c++;
                        int c3 = (c / (files.Count / 20));
                        if (c3 > c2)
                        {
                            Console.Write("{0}% ", c3 * 5);
                            c2 = c3;
                        }
                    }
                    catch (FtpException e) {
                        Console.WriteLine(String.Format("FTP Error: {0} {1}", e.ErrorCode, e.Message));
                    }
                }

                Console.WriteLine("{0} files created/updated.", transfered);
            }
        }
Beispiel #9
0
        public static FtpDirectoryInfo[] GetDirectories(string path)
        {
            FtpConnection conn = GetFtpConnection();

            conn.Open();
            conn.Login();
            FtpDirectoryInfo[] exists = conn.GetDirectories(path);
            conn.Close();
            conn.Dispose();
            return(exists);
        }
Beispiel #10
0
        private void ClearFtp()
        {
            var ftp = new FtpConnection(_ftpTestAccount.Server, _ftpTestAccount.UserName, _ftpTestAccount.Password);

            ftp.Open();
            ftp.Login();

            ClearFtp(ftp, "/");

            ftp.Close();
        }
Beispiel #11
0
        public static FtpFileInfo[] GetFiles(string path)
        {
            FtpConnection conn = GetFtpConnection();

            conn.Open();
            conn.Login();
            FtpFileInfo[] files = conn.GetFiles(path);
            conn.Close();
            conn.Dispose();
            return(files);
        }
        private void ClearFtp()
        {
            var ftp = new FtpConnection(_ftpServer, _userName, _password);

            ftp.Open();
            ftp.Login();

            ClearFtp(ftp, "/");

            ftp.Close();
        }
Beispiel #13
0
        public static bool DirectoryExists(string path)
        {
            FtpConnection conn = GetFtpConnection();

            conn.Open();
            conn.Login();
            bool exists = conn.DirectoryExists(path);

            conn.Close();
            conn.Dispose();
            return(exists);
        }
Beispiel #14
0
        private void BtnConnectClick(object sender, EventArgs e)
        {
            if (_ftp == null)
            {
                _ftp = new FtpConnection(tbServer.Text, tbUserName.Text, tbPassword.Text);
            }

            _ftp.Open();
            _ftp.Login();

            SetButtonsEnabledDisabled(true);
        }
Beispiel #15
0
 /// <summary>
 /// connect and login
 /// </summary>
 /// <returns></returns>
 public bool connect()
 {
     try
     {
         conn.Open();
         conn.Login();
     }
     catch (Exception e)
     {
         return(false);
     }
     return(true);
 }
Beispiel #16
0
 /// <summary>
 /// FTP初始化
 /// </summary>
 /// <param name="FtpServerIP">FTP连接地址</param>
 /// <param name="FtpRemotePath">指定FTP连接成功后的当前目录, 如果不指定即默认为根目录</param>
 /// <param name="FtpUserID">用户名</param>
 /// <param name="FtpPassword">密码</param>
 public FtpLib(string FtpServerIP, int FtpServerPort, string FtpRemotePath, string FtpUser, string FtpPassword)
 {
     try
     {
         ftpConnection = new FtpConnection(FtpServerIP, FtpServerPort, FtpUser, FtpPassword);
         ftpConnection.Open();  /* Open the FTP connection */
         ftpConnection.Login(); /* Login using previously provided credentials */
         NextDirectory(FtpRemotePath);
     }
     catch
     {
         throw;
     }
 }
Beispiel #17
0
 /// <summary>
 /// FTP初始化
 /// </summary>
 /// <param name="FtpServerIP">FTP连接地址</param>
 /// <param name="FtpRemotePath">指定FTP连接成功后的当前目录, 如果不指定即默认为根目录</param>
 /// <param name="FtpUserID">用户名</param>
 /// <param name="FtpPassword">密码</param>
 public FtpLib(string FtpServerIP, string FtpRemotePath, string FtpUserID, string FtpPassword, bool SSL)
 {
     try
     {
         var strs = FtpServerIP.Split(':');
         ftpConnection = new FtpConnection(strs[0], int.Parse(strs[1]), FtpUserID, FtpPassword);
         ftpConnection.Open();  /* Open the FTP connection */
         ftpConnection.Login(); /* Login using previously provided credentials */
         NextDirectory(FtpRemotePath);
     }
     catch
     {
         throw;
     }
 }
Beispiel #18
0
        private bool DownloadMapFiles()
        {
            int port = _remoteProc.GetFtpPort();

            using (var ftp = new FtpConnection(Setting.ServerAddr, port, "anonymous", "password"))
            {
                ftp.Open();
                ftp.Login();
                ftp.SetCurrentDirectory(MapDir);

                foreach (Map map in _maps)
                {
                    ftp.GetFile(map.FileName, Path.Combine(MapDir, map.FileName), false);
                }
            }
            return(true);
        }
Beispiel #19
0
 private bool VerificarConexaoServidor(BackgroundWorker status)
 {
     try
     {
         string ftppass = new FTPDAO(stringConexao).GetFTPPass();
         ftppass = StringCipher.Decrypt(ftppass, "mechtechforever");
         ftp     = new FtpConnection("ftp.acaciomelo.com", "*****@*****.**", ftppass);
         ftp.Open();
         ftp.Login();
         return(true);
     }
     catch
     {
         MessageBox.Show("O Sistema identificou que a conexão com o servidor não foi possível. Por favor, tente mais tarde.", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Warning);
         return(false);
     }
 }
Beispiel #20
0
        public void PublishToGitFTP(DeploymentModel model)
        {
            if (model.AzureDeployment)
            {
                var remoteProcess =
                    Process.Start("\"" + gitLocation + "\"", " --git-dir=\"" + fullRepoPath + "\" remote add blog " + model.AzureRepo);
                if (remoteProcess != null)
                {
                    remoteProcess.WaitForExit();
                }

                var pushProcess = Process.Start("\"" + gitLocation + "\"", " --git-dir=\"" + fullRepoPath + "\" push -f blog master");
                if (pushProcess != null)
                {
                    pushProcess.WaitForExit();
                }
            }
            else
            {
                using (ftp = new FtpConnection(model.FTPServer, model.FTPUsername, model.FTPPassword))
                {
                    try
                    {
                        ftp.Open();
                        ftp.Login();

                        if (!string.IsNullOrWhiteSpace(model.FTPPath))
                        {
                            if (!ftp.DirectoryExists(model.FTPPath))
                            {
                                ftp.CreateDirectory(model.FTPPath);
                            }

                            ftp.SetCurrentDirectory(model.FTPPath);
                        }

                        FtpBlogFiles(snowPublishPath, model.FTPPath);
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }
        }
Beispiel #21
0
        public void StartFTP()
        {
            string msg = string.Empty;

            if (dataBase_.dtSettlePrice.Rows.Count > 0)
            {
                if (File.Exists(ftpFileName_))
                {
                    File.Delete(ftpFileName_);
                }
                using (FtpConnection ftp = new FtpConnection(ftpIP_, ftpID_, ftpPassword_))
                {
                    using (StreamWriter streamWriter = new StreamWriter(ftpFileName_, false))
                    {
                        foreach (DataRow item in dataBase_.dtSettlePrice.Rows)
                        {
                            streamWriter.WriteLine(string.Format("{0,-16}{1,-6}  {2:000000.000000}  ", item["Pid"], item["YM"], item["SettlePrice"]));
                        }
                        streamWriter.Flush();
                    }

                    ftp.Open();
                    ftp.Login();
                    try
                    {
                        ftp.SetCurrentDirectory(ftpDirectory_);
                        ftp.PutFile(ftpFileName_, ftpFileName_);
                        msg = string.Format("{0}\t{1}:{2},Finish FTP Closing to {3}", DateTime.Now.ToString("hh:mm:ss.ffff"), MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ftpIP_);
                        srnItems_.lbLogs.InvokeIfNeeded(() => srnItems_.lbLogs.Items.Insert(0, msg));
                    }
                    catch (FtpException ex)
                    {
                        msg = String.Format("{0}\t{1}:{2}, Exception ErrCode: {3}, Message: {4}", DateTime.Now.ToString("hh:mm:ss.ffff"), MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ex.ErrorCode, ex.Message);
                        srnItems_.lbLogs.InvokeIfNeeded(() => srnItems_.lbLogs.Items.Insert(0, msg));
                    }
                }
            }
            else
            {
                msg = string.Format("{0}\t{1}:{2},本日無資料 !", DateTime.Now.ToString("hh:mm:ss.ffff"), MethodBase.GetCurrentMethod().ReflectedType.Name, MethodBase.GetCurrentMethod().Name, ftpIP_);
                srnItems_.lbLogs.InvokeIfNeeded(() => srnItems_.lbLogs.Items.Insert(0, msg));
            }
        }
Beispiel #22
0
        // Function to store ftp

        public bool s2FTP(String url, String name)
        {
            using (FtpConnection ftp = new FtpConnection("127.0.0.1", "rahul", "rahul"))
            {;           /* Open the FTP connection */

             ftp.Open(); /* Login using previously provided credentials */
             ftp.Login();
             try
             {
                 ftp.SetCurrentDirectory("/");
                 ftp.PutFile(@url, name);    /* upload c:\localfile.txt to the current ftp directory as file.txt */
             }
             catch (FtpException e)
             {
                 Console.WriteLine(String.Format("FTP Error: {0} {1}", e.ErrorCode, e.Message));
             } }

            return(true);
        }
Beispiel #23
0
        public bool FTPTransferHHTToPC(string hostIP, bool checkpermissionMode)
        {
            using (FtpConnection ftp = new FtpConnection(hostIP, userFTP, passwordFTP))
            {
                try
                {
                    ftp.Open();                      /* Open the FTP connection */
                    ftp.Login(userFTP, passwordFTP); /* Login using previously provided credentials */

                    string remoteFile = "";
                    string localFile  = "";

                    if (checkpermissionMode)
                    {
                        remoteFile = HHTDBPath + validateDBName;
                        localFile  = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).DirectoryName + "\\" + validateDBName;
                    }
                    else
                    {
                        remoteFile = HHTDBPath + DBName;
                        localFile  = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).DirectoryName + "\\" + DBName;
                    }


                    if (ftp.FileExists(remoteFile))                /* check that a file exists */
                    {
                        ftp.GetFile(remoteFile, localFile, false); /* download /incoming/file.txt as file.txt to current executing directory, overwrite if it exists */
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }
                catch (Exception ex)
                {
                    //Console.WriteLine(String.Format("FTP Error: {0} {1}", e.ErrorCode, e.Message));
                    log.Error(String.Format("Exception : {0}", ex.StackTrace));
                    return(false);
                }
            }
        }
Beispiel #24
0
        public void Execute(IActivityRequest request, IActivityResponse response)
        {
            String sourcePath     = request.Inputs["Source File Path"].AsString();
            String savePath       = request.Inputs["Destination File Path"].AsString();
            bool   overwriteLocal = Convert.ToBoolean(request.Inputs["Overwrite Local File"].AsString());

            using (FtpConnection ftp = new FtpConnection(settings.FtpServer, settings.Port, settings.UserName, settings.Password))
            {
                ftp.Open();
                ftp.Login();

                if (ftp.FileExists(sourcePath))
                {
                    ftp.GetFile(sourcePath, savePath, overwriteLocal);
                }
                else
                {
                    response.LogErrorMessage("File does not exist at " + sourcePath);
                }
            }
        }
Beispiel #25
0
        public static void getFile(ref string UserName, ref string PassWord, ref string ServerName, ref string FileName)
        {
            using (FtpConnection ftp = new FtpConnection("ServerName", "UserName", "PassWord"))
            {
                ftp.Open();                                   /* Open the FTP connection */
                ftp.Login();                                  /* Login using previously provided credentials */

                if (ftp.DirectoryExists("/incoming"))         /* check that a directory exists */
                {
                    ftp.SetCurrentDirectory("/incoming");     /* change current directory */
                }
                if (ftp.FileExists("/incoming/file.txt"))     /* check that a file exists */
                {
                    ftp.GetFile("/incoming/file.txt", false); /* download /incoming/file.txt as file.txt to current executing directory, overwrite if it exists */
                }
                //do some processing

                try
                {
                    ftp.SetCurrentDirectory("/outgoing");
                    ftp.PutFile(@"c:\localfile.txt", "file.txt"); /* upload c:\localfile.txt to the current ftp directory as file.txt */
                }
                catch (FtpException e)
                {
                    Console.WriteLine(String.Format("FTP Error: {0} {1}", e.ErrorCode, e.Message));
                }

                foreach (var dir in ftp.GetDirectories("/incoming/processed"))
                {
                    Console.WriteLine(dir.Name);
                    Console.WriteLine(dir.CreationTime);
                    foreach (var file in dir.GetFiles())
                    {
                        Console.WriteLine(file.Name);
                        Console.WriteLine(file.LastAccessTime);
                    }
                }
            }
        } // End getFile()
Beispiel #26
0
        private void GetFile()
        {
            string Newlocation = "";
            string ftpusername = "******";
            string ftppassword = "******";
            string ip          = "172.26.50.199";
            int    FtpPort     = Convert.ToInt16("21");
            string Actfile     = "sample.txt";


            int    cnt  = Actfile.LastIndexOf('.');
            string Extn = Actfile.Substring(Actfile.LastIndexOf('.'), Actfile.Length - Actfile.LastIndexOf('.'));

            using (FtpConnection _ftp = new FtpConnection(ip, FtpPort, ftpusername, ftppassword))
            {
                try
                {
                    _ftp.Open();
                    _ftp.Login();


                    string Ftpfile = "Notifications\\sample.txt";
                    Newlocation = "D:\\Syed\\Downloaded";

                    _ftp.GetFile(Ftpfile, Newlocation + "\\" + "sample.txt", false);
                }
                catch (FtpException ex)
                {
                    throw ex;
                }
                finally
                {
                    _ftp.Close();

                    string             strDURL    = "D:\\Syed\\Downloaded\\sample.txt";
                    System.IO.FileInfo toDownload = new System.IO.FileInfo(strDURL);
                }
            }
        }
Beispiel #27
0
        private static void DownloadFiles(ServerInfo server)
        {
            string tempFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + Path.DirectorySeparatorChar + "MapUpdater";

            ConnectionInfo connection = server.MinecraftConnection;

            if (connection.Type == ConnectionType.Ftp)
            {
                using (FtpConnection ftp = new FtpConnection(connection.Address, 21, connection.Username, connection.Password))
                {
                    ftp.Open();
                    ftp.Login();
                    ftp.SetCurrentDirectory(connection.WorldsFolder);

                    if (ftp.GetCurrentDirectory() != connection.WorldsFolder)
                    {
                        Console.WriteLine("WorldsFolder does not exist on server");
                    }

                    DownloadDirectory(ftp, server.World.Name, tempFolder + Path.DirectorySeparatorChar + server.World.Name);
                }
            }
        }
Beispiel #28
0
        private void sendViaFTP()
        {
            string _remoteHost = "ftp.bfi.net.in";
            string _remoteUser = "******";
            string _remotePass = "******";
            string source      = @"C:\Users\snarasim\Downloads\test.pdf";
            string destination = "/test.pdf";

            using (FtpConnection ftp = new FtpConnection(_remoteHost, _remoteUser, _remotePass))
            {
                try
                {
                    ftp.Open();  // Open the FTP connection
                    ftp.Login(); // Login using previously provided credentials
                    ftp.PutFile(source, destination);
                    MessageBox.Show("Done");
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
            }
        }
Beispiel #29
0
        public bool FTPTransferPCToHHT(string hostIP)
        {
            using (FtpConnection ftp = new FtpConnection(hostIP, userFTP, passwordFTP))
            {
                try
                {
                    ftp.Open();                      /* Open the FTP connection */
                    ftp.Login(userFTP, passwordFTP); /* Login using previously provided credentials */

                    string remoteFile = HHTDBPath + DBName;
                    string localFile  = new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).DirectoryName + "\\" + DBName;

                    ftp.PutFile(localFile, remoteFile);
                    return(true);
                }
                catch (Exception ex)
                {
                    //Console.WriteLine(String.Format("FTP Error: {0} {1}", e.ErrorCode, e.Message));
                    log.Error(String.Format("Exception : {0}", ex.StackTrace));
                    return(false);
                }
            }
        }
Beispiel #30
0
        public bool connect(string user, string pass)
        {
            bool ret = false;

            logger.pushOperation("FTP.connect");
            try
            {
                sFTP = new FtpConnection(host, port);
                sFTP.Open();
                sFTP.Login(user, pass);
                ret = sFTP.DirectoryExists("/");
            }
            catch (Exception e)
            {
                ret = false;
                logger.log("Erro ao conectar FTP: " + e.Message, Logger.LogType.ERROR, e, false);
            }
            finally
            {
                logger.releaseOperation();
            }

            return(ret);
        }