Exemplo n.º 1
0
 static void Main()
 {
     var testConnection = new FtpConnection("SERVER", "USER", "PASSWORD");
     var testFileLocation = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "/testFile.txt";
     var testByteArray = File.ReadAllBytes(testFileLocation);
     testConnection.UploadFile(testByteArray, "testName", "/SOMEPATH");
 }
Exemplo n.º 2
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MlstCommandHandler"/> class.
 /// </summary>
 /// <param name="connection">The FTP connection this command handler is created for.</param>
 public MlstCommandHandler(FtpConnection connection)
     : base(connection, "MLST", "MLSD")
 {
     connection.Data.ActiveMlstFacts.Clear();
     foreach (var knownFact in _knownFacts)
         connection.Data.ActiveMlstFacts.Add(knownFact);
 }
 private static string FeatureStatus(FtpConnection connection)
 {
     var result = new StringBuilder();
     result.Append("MLST ");
     foreach (var fact in _knownFacts)
     {
         result.AppendFormat("{0}{1};", fact, connection.Data.ActiveMlstFacts.Contains(fact) ? "*" : string.Empty);
     }
     return result.ToString();
 }
Exemplo n.º 4
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);
                }
            }
        }
Exemplo n.º 5
0
        private bool PutFile(FtpConnection ftp, string file)
        {
            string ftpPart    = file.Remove(0, file.IndexOf(@"Interface\AddOns\") + (@"Interface\AddOns\").Length);
            string folderName = ftpPart.Remove(ftpPart.LastIndexOf(@"\"));
            string fileName   = ftpPart.Remove(0, ftpPart.LastIndexOf(@"\") + 1);

            if (!currentDir.Equals(folderName))
            {
                ftp.SetCurrentDirectory(@"\" + folderName);
                currentDir         = folderName;
                currentDirFileInfo = ftp.GetFiles();
            }

            FileInfo localFileInfo = new FileInfo(file);

            FtpFileInfo ftpFileInfo = null;

            foreach (FtpFileInfo info in currentDirFileInfo)
            {
                if (info.Name.Equals(fileName))
                {
                    ftpFileInfo = info;
                }
            }

            if (ftpFileInfo == null)
            {
                ftp.PutFile(file, fileName);
                return(true);
            }
            else
            {
                DateTime ftpTime = ftpFileInfo.LastWriteTimeUtc ?? DateTime.MinValue;
                if (ftpTime < localFileInfo.LastWriteTimeUtc)
                {
                    ftp.PutFile(file, fileName);
                    return(true);
                }
            }

            return(false);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Upload Files
        /// </summary>
        private void UploadFiles()
        {
            if (this.FileNames == null)
            {
                this.Log.LogError("The required fileNames attribute has not been set for FTP.");
                return;
            }

            using (FtpConnection ftpConnection = this.CreateFtpConnection())
            {
                this.LogTaskMessage("Uploading Files");
                if (!string.IsNullOrEmpty(this.WorkingDirectory))
                {
                    this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Setting Local Directory: {0}", this.WorkingDirectory));
                    FtpConnection.SetLocalDirectory(this.WorkingDirectory);
                }

                ftpConnection.LogOn();

                if (!string.IsNullOrEmpty(this.RemoteDirectoryName))
                {
                    this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Setting Current Directory: {0}", this.RemoteDirectoryName));
                    ftpConnection.SetCurrentDirectory(this.RemoteDirectoryName);
                }

                foreach (string fileName in this.FileNames.Select(item => item.ItemSpec))
                {
                    try
                    {
                        if (File.Exists(fileName))
                        {
                            this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Uploading: {0}", fileName));
                            ftpConnection.PutFile(fileName);
                        }
                    }
                    catch (FtpException ex)
                    {
                        this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "There was an error uploading file: {0}. The Error Details are \"{1}\" and error code is {2} ", fileName, ex.Message, ex.ErrorCode));
                    }
                }
            }
        }
Exemplo n.º 7
0
        private void btnIISftp_login_Click(object sender, EventArgs e)
        {
            try
            {
                this.iis_ftpconnection = this.Get171Connection();
                this.iis_ftpconnection.Login();
                this.btnIISftp_cwd.Enabled   = true;
                this.btnIISftp_files.Enabled = true;
                this.btnIISftp_pwd.Enabled   = true;
                this.btnIISftp_login.Enabled = false;
            }
            catch (Exception ex)
            {
                Console.WriteLine("serv-u 登录失败" + ex.Message);

                this.btnIISftp_cwd.Enabled   = false;
                this.btnIISftp_files.Enabled = false;
                this.btnIISftp_pwd.Enabled   = true;
                this.btnIISftp_login.Enabled = true;
            }
        }
Exemplo n.º 8
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);
                }
            }
        }
Exemplo n.º 9
0
        /// <summary>
        ///		Libera la instancia
        /// </summary>
        private void Release(bool waitReply)
        {
            FtpConnection connection = Connection;

            if (connection != null)
            {
                try
                {
                    if (waitReply)
                    {
                        // Espera los resultados:
                        //		226: ACK predeterminado
                        //		150: Si el stream se abrió pero nunca se ha enviado nada, podemos salir sin problema
                        Process(() => new Commands.FtpEmptyStreamCommand(connection, new int[] { 226, 150 }).Send());
                    }
                }
                finally
                {                         // en transferencias largas, puede que se haya cerrado el socket, sin embargo,
                                          // lo debemos señalar en el cliente
                }
            }
        }
Exemplo n.º 10
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);
                }
            }
        }
Exemplo n.º 11
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()
        /// <summary>
        ///		Inicializa el stream para utilizar (o no) SSL/TLS
        /// </summary>
        private void InitializeProtocol(FtpConnection connection, FtpTransportStream data)
        {
            switch (connection.Client.Protocol)
            {
            case FtpClient.FtpProtocol.Ftp:                     // Directo. Simplemente se limpian los datos
                data.LeaveSsl();
                break;

            case FtpClient.FtpProtocol.FtpS:                     // ... se cambia a un túnel SSL
                data.UpgradeToSsl(connection.Client.ClientParameters.GetSslProtocol());
                break;

            case FtpClient.FtpProtocol.FtpES:                     // informa primero sobre un canal limpio y después se cambia a SSL
                data.LeaveSsl();
                new Commands.Server.FtpAuthCommand(connection).Send();
                data.UpgradeToSsl(connection.Client.ClientParameters.GetSslProtocol());
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Exemplo n.º 13
0
        internal ResumeCapability Connect(FtpConnection connection, bool addTraceListener = true, EventHandler <FtpGetListingEventArgs> onGetListingDataReceived = null)
        {
            _ftpClient = new FtpClient
            {
                EnableThreadSafeDataConnections = false,
                DataConnectionType = connection.UsePassiveMode ? FtpDataConnectionType.PASV : FtpDataConnectionType.PORT,
                Host = connection.Address,
                Port = connection.Port
            };
            if (addTraceListener)
            {
                FtpTrace.AddListener(TraceListener);
            }

            Connection = connection;
            _ftpClient.BeforeAuthentication += OnBeforeAuthentication;
            _ftpClient.Connected            += OnConnected;
            if (onGetListingDataReceived != null)
            {
                _ftpClient.GetListingDataReceived += onGetListingDataReceived;
            }
            _ftpClient.Connect();

            var resume = ResumeCapability.None;
            var r      = FtpClient.Execute("APPE");

            if (!r.Message.Contains("command not recognized"))
            {
                resume |= ResumeCapability.Append;
            }

            r = FtpClient.Execute("REST");
            if (!r.Message.Contains("command not recognized"))
            {
                resume |= ResumeCapability.Restart;
            }
            return(resume);
        }
Exemplo n.º 14
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);
                }
            }
        }
Exemplo n.º 15
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);
                }
            }
        }
Exemplo n.º 16
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);
                }
            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// Delete given files from the FTP Directory
        /// </summary>
        private void DeleteFiles()
        {
            if (this.FileNames == null)
            {
                this.Log.LogError("The required FileNames attribute has not been set for FTP.");
                return;
            }

            using (FtpConnection ftpConnection = this.CreateFtpConnection())
            {
                ftpConnection.LogOn();
                this.LogTaskMessage("Deleting Files");
                if (!string.IsNullOrEmpty(this.RemoteDirectoryName))
                {
                    this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Setting Current Directory: {0}", this.RemoteDirectoryName));
                    ftpConnection.SetCurrentDirectory(this.RemoteDirectoryName);
                }

                foreach (string fileName in this.FileNames.Select(item => item.ItemSpec))
                {
                    try
                    {
                        this.LogTaskMessage(string.Format(CultureInfo.CurrentCulture, "Deleting: {0}", fileName));
                        ftpConnection.DeleteFile(fileName);
                    }
                    catch (FtpException ex)
                    {
                        if (ex.Message.Contains("550"))
                        {
                            continue;
                        }

                        this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "There was an error in deleting file: {0}. The Error Details are \"{1}\" and error code is {2} ", fileName, ex.Message, ex.ErrorCode));
                    }
                }
            }
        }
Exemplo n.º 18
0
        /// <summary>
        ///		Abre un stream de datos en modo pasivo
        /// </summary>
        internal FtpPassiveStream Open(FtpConnection connection)
        {
            string host    = null;
            int    port    = 0;
            bool   passive = false;

            // Intenta pasar a modo pasivo (EPSV o PSV)
            if (connection.Server.Features.HasFeature("EPSV"))
            {
                passive = TransferExtendedPassiveMode(connection, ref host, ref port);
            }
            else
            {
                passive = TransferPassiveMode(connection, ref host, ref port);
            }
            // Si no ha podido pasar a modo pasivo o no se ha interpretado correctamente el host lanza una excepción
            if (!passive)
            {
                throw new Exceptions.FtpException("No se ha podido pasar a modo pasivo");
            }
            if (string.IsNullOrEmpty(host))
            {
                throw new Exceptions.FtpException("No se pudo obtener la dirección del host al pasar a modo pasivo");
            }
            // Asigna el proxy
            if (connection.Client.ClientParameters.ProxyConnect != null)
            {
                Socket socket = connection.Client.ClientParameters.ProxyConnect(new DnsEndPoint(host, port));

                if (socket != null)
                {
                    return(new FtpPassiveStream(connection, socket));
                }
            }
            // Abre la conexión de datos
            return(OpenDataStream(connection, host, port));
        }
Exemplo n.º 19
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);
        }
Exemplo n.º 20
0
        private static void UploadMapImages(ServerInfo server)
        {
            string         currentDirectory = Environment.CurrentDirectory;
            ConnectionInfo connection       = server.WebConnection;

            if (connection.Type == ConnectionType.Ftp)
            {
                using (FtpConnection ftp = new FtpConnection(connection.Address, 21, connection.Username, connection.Password))
                {
                    ftp.Open();
                    ftp.Login();
                    ftp.SetCurrentDirectory(connection.ImagesFolder);
                    if (ftp.GetCurrentDirectory() != connection.ImagesFolder)
                    {
                        Console.WriteLine("ImagesFolder does not exist on server");
                    }

                    foreach (string file in Directory.GetFiles(Environment.CurrentDirectory, "*.png"))
                    {
                        ftp.PutFile(file);
                    }
                }
            }
        }
Exemplo n.º 21
0
        public MainForm()
        {
            InitializeComponent();

            _ftp = null;

            string
                currentDirectory = Directory.GetCurrentDirectory();

            if (!Directory.Exists(currentDirectory = Path.Combine(currentDirectory.Substring(0, currentDirectory.LastIndexOf("bin", currentDirectory.Length - 1)), "ftproot")))
            {
                Directory.CreateDirectory(currentDirectory);
            }

            if (!Directory.Exists(_directoryDownload = Path.Combine(currentDirectory, "download")))
            {
                Directory.CreateDirectory(_directoryDownload);
            }

            if (!Directory.Exists(_directoryUpload = Path.Combine(currentDirectory, "upload")))
            {
                Directory.CreateDirectory(_directoryUpload);
            }
        }
Exemplo n.º 22
0
        public void ClearFtp(FtpConnection ftp, string directory)
        {
            ftp.SetCurrentDirectory(directory);
            var dirs = ftp.GetDirectories();

            foreach (var dir in dirs)
            {
                if ((dir.Name != ".") && (dir.Name != ".."))
                {
                    ClearFtp(ftp, dir.Name); //Recursive call
                    ftp.RemoveDirectory(dir.Name);
                }
            }

            foreach (var file in ftp.GetFiles())
            {
                ftp.RemoveFile(file.Name);
            }

            if (ftp.GetCurrentDirectory() != "/")
            {
                ftp.SetCurrentDirectory("..");
            }
        }
Exemplo n.º 23
0
        public void UploadOrders()
        {
            try
            {
                Xceed.Ftp.Licenser.LicenseKey = "FTN42-K40Z3-DXCGS-PYGA";
                //Xceed.FileSystem.Licenser.LicenseKey = "";

                if (!UploadWork)
                {
                    try
                    {
                        UploadWork = true;
                        SqlConnection db_connection = new SqlConnection(prop.Connection_string);
                        db_connection.Open();
                        file.WriteLine(DateTime.Now.ToString("g", ci) + " [+] Выбираем заказы на экспорт");
                        file.Flush();
                        SqlCommand db_command = new SqlCommand("SELECT [number], [auto_export], [id_place] FROM [order] WHERE [auto_export] > 0;", db_connection);
                        SqlDataAdapter db_adapter = new SqlDataAdapter(db_command);
                        DataTable tbl = new DataTable();
                        db_adapter.Fill(tbl);

                        foreach (DataRow rw in tbl.Rows)
                        {
                            try
                            {
                                file.WriteLine(DateTime.Now.ToString("g", ci) + " [+] Подготавливаем к выгрузке заказ " + rw["number"].ToString().Trim());
                                file.Flush();
                                PSA.Lib.Util.ExportOrder.autoExport((int)rw["auto_export"], rw["number"].ToString().Trim());
                                db_command = new SqlCommand("SELECT [server], [path], [username], [password] FROM [place] WHERE [id_place] = " + rw["id_place"], db_connection);
                                db_adapter = new SqlDataAdapter(db_command);
                                DataTable ptbl = new DataTable();
                                db_adapter.Fill(ptbl);
                                if (ptbl.Rows.Count > 0)
                                {
                                    DataRow place = ptbl.Rows[0];
                                    file.WriteLine(DateTime.Now.ToString("g", ci) + " [+] Выгружаем заказ " + rw["number"].ToString().Trim() + " на " + place["server"].ToString().Trim() + " в " + place["path"].ToString().Trim());
                                    file.Flush();
                                    using (FtpConnection connection = new FtpConnection(
                                        place["server"].ToString().Trim(),
                                        place["username"].ToString().Trim(),
                                        place["password"].ToString().Trim()))
                                    {
                                        connection.Encoding = Encoding.GetEncoding(1251);

                                        file.WriteLine("from: " + prop.Dir_export + "\\auto_export\\" + rw["number"].ToString().Trim() + "\\");
                                        file.Flush();
                                        DiskFolder source = new DiskFolder(prop.Dir_export + "\\auto_export\\" + rw["number"].ToString().Trim() + "\\");

                                        string ftp_to = place["path"].ToString().Trim() + rw["number"].ToString().Trim() + "/";
                                        if (ftp_to.Substring(0, 1) == "/") ftp_to = ftp_to.Substring(1);
                                        file.WriteLine("to: " + ftp_to);
                                        file.Flush();
                                        try
                                        {
                                            FtpFolder _ftp_to = new FtpFolder(connection, ftp_to);
                                            _ftp_to.Delete();
                                        }
                                        catch { }

                                        FtpFolder destination = new FtpFolder(connection, ftp_to);

                                        StreamWriter _tmp = new StreamWriter(prop.Dir_export + "\\auto_export\\" + rw["number"].ToString().Trim() + "\\.lock");
                                        _tmp.Write("\n");
                                        _tmp.Close();
                                        db_command = new SqlCommand("UPDATE [order] SET [status_export] = 'Началась выгрузка', [status_export_date] = getdate() WHERE [number] = '" + rw["number"].ToString().Trim() + "'", db_connection);
                                        db_command.ExecuteNonQuery();
                                        source.CopyFilesTo(destination, true, true);
                                        FtpFile _lock = new FtpFile(connection, ftp_to + ".lock");
                                        _lock.Delete();
                                        db_command = new SqlCommand("UPDATE [order] SET [auto_export] = -1, [status_export] = 'Отправлен', [status] = '500000', [status_export_date] = getdate() WHERE [number] = '" + rw["number"].ToString().Trim() + "'", db_connection);
                                        db_command.ExecuteNonQuery();
                                        file.WriteLine(DateTime.Now.ToString("g", ci) + " [+] Выгружен заказ " + rw["number"].ToString().Trim());
                                        file.Flush();
                                        Directory.Delete(prop.Dir_export + "\\auto_export\\" + rw["number"].ToString().Trim() + "\\", true);
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                db_command = new SqlCommand("UPDATE [order] SET [status_export] = '" + ex.Message +
                                                            "', [status_export_date] = getdate() WHERE [number] = '" + rw["number"].ToString().Trim() + "'",
                                                            db_connection);
                                db_command.ExecuteNonQuery();
                                file.WriteLine(DateTime.Now.ToString("g", ci) + " [!] Ошибка выгрузки заказа " + ex.Message + "\n" + ex.Source + "\n" + ex.StackTrace);
                                file.Flush();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        file.WriteLine(DateTime.Now.ToString("g", ci) + " [!] Ошибка выгрузки заказов " + ex.Message + "\n" + ex.Source + "\n" + ex.StackTrace);
                        file.Flush();
                    }
                    finally
                    {
                        UploadWork = false;
                    }
                }
            }
            catch (Exception ex)
            {
                file.WriteLine(DateTime.Now.ToString("g", ci) + " [!] Глобальная ошибка по время отправления " + ex.Message);
                file.Flush();
            }
        }
Exemplo n.º 24
0
        public void DoAction()
        {
            string strProcedureName =
                string.Format(
                    "{0}.{1}",
                    className,
                    MethodBase.GetCurrentMethod().Name);

            WriteLog.Instance.WriteBeginSplitter(strProcedureName);
            try
            {
                if (uploadType == "FTP")
                {
                    WriteLog.Instance.Write(string.Format("向FTP[{0}]上传文件[{1}],文件内容:[{2}]", address, fileName, strData), strProcedureName);
                    int port = 21;
                    int.TryParse(strPort, out port);
                    string FTPpath      = string.Format(@"{0}{1}\", AppDomain.CurrentDomain.BaseDirectory, uploadfilePath);
                    string fullFileName = FTPpath + fileName;
                    string remotefile   = string.Format(@"{0}\{1}", uploadfilePath, fileName);
                    using (FtpConnection ftp = new FtpConnection(address, port, userID, pwd))
                    {
                        try
                        {
                            ftp.Open();
                            ftp.Login();
                            if (!Directory.Exists(FTPpath))
                            {
                                Directory.CreateDirectory(FTPpath);
                            }
                            if (!System.IO.File.Exists(fullFileName))
                            {
                                System.IO.FileStream   fs = System.IO.File.Create(fullFileName);
                                System.IO.StreamWriter sw = new System.IO.StreamWriter(fs, Encoding.Default);//ANSI编码格式
                                sw.Write(strData);
                                sw.Flush();
                                sw.Close();
                                fs.Close();
                            }
                            ftp.PutFile(fullFileName, remotefile);
                            WriteLog.Instance.Write("文件上传成功!", strProcedureName);
                            ftp.Close();
                        }
                        catch (Exception error)
                        {
                            WriteLog.Instance.Write(error.Message, strProcedureName);
                            XtraMessageBox.Show(
                                error.Message,
                                "系统信息",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
                        }
                        finally
                        {
                            if (System.IO.File.Exists(fullFileName))
                            {
                                System.IO.File.Delete(fullFileName);
                            }
                        }
                    }
                }
                else if (uploadType == "HTTP")
                {
                }
                else if (uploadType == "ShareFolder")
                {
                }
            }
            finally
            {
                WriteLog.Instance.WriteEndSplitter(strProcedureName);
            }
        }
Exemplo n.º 25
0
 /// <summary>
 /// Initializes a new instance of the <see cref="XmkdCommandHandler"/> class.
 /// </summary>
 /// <param name="connection">The connection to create this command handler for</param>
 public XmkdCommandHandler(FtpConnection connection)
     : base(connection, "XMKD")
 {
 }
Exemplo n.º 26
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RetrCommandHandler"/> class.
 /// </summary>
 /// <param name="connection">The connection to create this command handler for</param>
 public RetrCommandHandler(FtpConnection connection)
     : base(connection, "RETR")
 {
 }
Exemplo n.º 27
0
        public void PublishToGitFTP(DeploymentModel model)
        {
            if (model.GitDeployment)
            {
                Logger.Debug("Executing git add");

                var addProcess          = new Process();
                var addProcessStartInfo = new ProcessStartInfo("\"" + gitLocation + "\"")
                {
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true,
                    UseShellExecute        = false,
                    Arguments = " --git-dir=\"" + fullPublishGitPath + "\" --work-tree=\"" + publishGitPath + "\" add -A"
                };
                addProcess.StartInfo           = addProcessStartInfo;
                addProcess.OutputDataReceived += (sender, args) => Logger.Debug(args.Data);
                addProcess.ErrorDataReceived  += (sender, args) => Logger.Debug(args.Data);
                addProcess.Start();
                addProcess.BeginOutputReadLine();
                addProcess.BeginErrorReadLine();
                addProcess.WaitForExit();

                Logger.Debug("git add process to exited");

                Logger.Debug("Executing git email config process");

                var emailProcess          = new Process();
                var emailProcessStartInfo = new ProcessStartInfo("\"" + gitLocation + "\"")
                {
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true,
                    UseShellExecute        = false,
                    Arguments = " --git-dir=\"" + fullPublishGitPath + "\" --work-tree=\"" + publishGitPath + "\" config user.email \"[email protected]\""
                };
                emailProcess.StartInfo           = emailProcessStartInfo;
                emailProcess.OutputDataReceived += (sender, args) => Logger.Debug(args.Data);
                emailProcess.ErrorDataReceived  += (sender, args) => Logger.Debug(args.Data);
                emailProcess.Start();
                emailProcess.BeginOutputReadLine();
                emailProcess.BeginErrorReadLine();
                emailProcess.WaitForExit();
                Logger.Debug("git email config process to exited");

                Logger.Debug("Executing git name config process");

                var userProcess          = new Process();
                var userProcessStartInfo = new ProcessStartInfo("\"" + gitLocation + "\"")
                {
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true,
                    UseShellExecute        = false,
                    Arguments = " --git-dir=\"" + fullPublishGitPath + "\" --work-tree=\"" + publishGitPath + "\" config user.name \"barbato\""
                };
                userProcess.StartInfo           = userProcessStartInfo;
                userProcess.OutputDataReceived += (sender, args) => Logger.Debug(args.Data);
                userProcess.ErrorDataReceived  += (sender, args) => Logger.Debug(args.Data);
                userProcess.Start();
                userProcess.BeginOutputReadLine();
                userProcess.BeginErrorReadLine();
                userProcess.WaitForExit();

                Logger.Debug("git name config process to exited");

                Logger.Debug("Executing git commit");

                var commitProcess          = new Process();
                var commitProcessStartInfo = new ProcessStartInfo("\"" + gitLocation + "\"")
                {
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true,
                    UseShellExecute        = false,
                    Arguments = " --git-dir=\"" + fullPublishGitPath + "\" --work-tree=\"" + publishGitPath +
                                "\" commit -a -m \"Static Content Regenerated\""
                };
                commitProcess.StartInfo           = commitProcessStartInfo;
                commitProcess.OutputDataReceived += (sender, args) => Logger.Debug(args.Data);
                commitProcess.ErrorDataReceived  += (sender, args) => Logger.Debug(args.Data);
                commitProcess.Start();
                commitProcess.BeginOutputReadLine();
                commitProcess.BeginErrorReadLine();
                commitProcess.WaitForExit();

                Logger.Debug("git commit process to exited");

                Logger.Debug("Executing git push");

                var pushProcess          = new Process();
                var pushProcessStartInfo = new ProcessStartInfo("\"" + gitLocation + "\"")
                {
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true,
                    UseShellExecute        = false,
                    Arguments = " --git-dir=\"" + fullPublishGitPath + "\" push -f origin master"
                };
                pushProcess.OutputDataReceived += (sender, args) => Logger.Debug(args.Data);
                pushProcess.ErrorDataReceived  += (sender, args) => Logger.Debug(args.Data);
                pushProcess.StartInfo           = pushProcessStartInfo;
                pushProcess.Start();
                pushProcess.BeginOutputReadLine();
                pushProcess.BeginErrorReadLine();
                pushProcess.WaitForExit();

                Logger.Debug("git push process to exited");
            }
            else
            {
                using (ftp = new FtpConnection(model.FTPServer, model.FTPUsername, model.FTPPassword))
                {
                    try
                    {
                        ftp.Open();
                        ftp.Login();

                        if (!string.IsNullOrWhiteSpace(model.FTPPath))
                        {
                            var parrentDirectory = String.Format("/{0}", Path.GetDirectoryName(model.FTPPath).Replace(Path.DirectorySeparatorChar, '/'));
                            /* Get name of the directory */
                            var checkingDirectory = String.Format("{0}", Path.GetFileName(model.FTPPath)).ToLower();
                            /* Get all child directories info of the parent directory */
                            var ftpDirectories = ftp.GetDirectories(parrentDirectory);
                            /* check if the given directory exists in the returned result */
                            var exists = ftpDirectories.Any(d => d.Name.ToLower() == checkingDirectory);

                            if (!exists)
                            {
                                ftp.CreateDirectory(model.FTPPath);
                            }

                            ftp.SetCurrentDirectory(model.FTPPath);
                        }

                        FtpBlogFiles(publishGitPath, model.FTPPath);
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }
        }
Exemplo n.º 28
0
 /// <summary>
 /// Initializes a new instance of the <see cref="StorCommandHandler"/> class.
 /// </summary>
 /// <param name="connection">The connection this command handler is created for</param>
 public StorCommandHandler(FtpConnection connection)
     : base(connection, "STOR")
 {
 }
Exemplo n.º 29
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RntoCommandHandler"/> class.
 /// </summary>
 /// <param name="connection">The connection to create this command handler for</param>
 public RntoCommandHandler(FtpConnection connection)
     : base(connection, "RNTO")
 {
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="FtpCommandHandlerExtension"/> class.
 /// </summary>
 /// <param name="connection">The connection this instance is used for</param>
 /// <param name="extensionFor">The name of the command this extension is for</param>
 /// <param name="name">The command name</param>
 /// <param name="alternativeNames">Alternative names</param>
 protected FtpCommandHandlerExtension([NotNull] FtpConnection connection, [NotNull] string extensionFor, [NotNull] string name, [NotNull, ItemNotNull] params string[] alternativeNames)
     : base(connection, name, alternativeNames)
 {
     ExtensionFor = extensionFor;
 }
Exemplo n.º 31
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FtpCommandHandler"/> class.
 /// </summary>
 /// <param name="connection">The connection this instance is used for</param>
 /// <param name="name">The command name</param>
 /// <param name="alternativeNames">Alternative names</param>
 protected FtpCommandHandler([NotNull] FtpConnection connection, [NotNull] string name, [NotNull, ItemNotNull] params string[] alternativeNames)
     : base(connection, name, alternativeNames)
 {
 }
Exemplo n.º 32
0
 /// <summary>
 /// Initializes a new instance of the <see cref="HelpCommandHandler"/> class.
 /// </summary>
 /// <param name="connection">The connection to create this command handler for</param>
 public HelpCommandHandler(FtpConnection connection)
     : base(connection, "HELP")
 {
 }
Exemplo n.º 33
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AborCommandHandler"/> class.
 /// </summary>
 /// <param name="connection">The connection to create this command handler for</param>
 public AborCommandHandler(FtpConnection connection)
     : base(connection, "ABOR")
 {
 }
Exemplo n.º 34
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PbszCommandHandler"/> class.
 /// </summary>
 /// <param name="connection">The connection to create this command handler for</param>
 public PbszCommandHandler(FtpConnection connection)
     : base(connection, "PBSZ")
 {
 }
Exemplo n.º 35
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SizeCommandHandler"/> class.
 /// </summary>
 /// <param name="connection">The connection to create this command handler for</param>
 public SizeCommandHandler(FtpConnection connection)
     : base(connection, "SIZE")
 {
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="ListCommandHandler"/> class.
 /// </summary>
 /// <param name="connection">The connection to create this command handler for</param>
 public ListCommandHandler(FtpConnection connection)
     : base(connection, "LIST", "NLST", "LS")
 {
 }
Exemplo n.º 37
0
 /// <summary>
 /// Initializes a new instance of the <see cref="OptsCommandHandler"/> class.
 /// </summary>
 /// <param name="connection">The connection to create this command handler for</param>
 public OptsCommandHandler(FtpConnection connection)
     : base(connection, "OPTS")
 {
     Extensions = new Dictionary<string, FtpCommandHandlerExtension>(StringComparer.OrdinalIgnoreCase);
 }
Exemplo n.º 38
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RnfrCommandHandler"/> class.
 /// </summary>
 /// <param name="connection">The connection to create this command handler for</param>
 public RnfrCommandHandler(FtpConnection connection)
     : base(connection, "RNFR")
 {
 }
Exemplo n.º 39
0
 /// <summary>
 /// Initializes a new instance of the <see cref="OptsCommandHandler"/> class.
 /// </summary>
 /// <param name="connection">The connection to create this command handler for</param>
 public OptsCommandHandler(FtpConnection connection)
     : base(connection, "OPTS")
 {
     Extensions = new Dictionary <string, FtpCommandHandlerExtension>(StringComparer.OrdinalIgnoreCase);
 }
Exemplo n.º 40
0
 /// <summary>
 /// Initializes a new instance of the <see cref="QuitCommandHandler"/> class.
 /// </summary>
 /// <param name="connection">The connection to create this command handler for</param>
 public QuitCommandHandler(FtpConnection connection)
     : base(connection, "QUIT", "LOGOUT")
 {
 }
Exemplo n.º 41
0
 /// <summary>
 /// ����Ftp
 /// </summary>
 /// <returns></returns>
 private FtpConnection FtpConn()
 {
     ftp=new FtpConnection();
     ftp.Connect(this.FtpIP,this.FtpUserName,this.FtpPassord);
     return ftp;
 }
Exemplo n.º 42
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RestCommandHandler"/> class.
 /// </summary>
 /// <param name="connection">The connection to create this command handler for</param>
 public RestCommandHandler(FtpConnection connection)
     : base(connection, "REST")
 {
 }
Exemplo n.º 43
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PasvCommandHandler"/> class.
 /// </summary>
 /// <param name="connection">The connection this command handler is created for</param>
 public PasvCommandHandler(FtpConnection connection)
     : base(connection, "PASV", "EPSV")
 {
 }
Exemplo n.º 44
0
 /// <summary>
 /// Initializes a new instance of the <see cref="PassCommandHandler"/> class.
 /// </summary>
 /// <param name="connection">The connection to create this command handler for</param>
 public PassCommandHandler(FtpConnection connection)
     : base(connection, "PASS")
 {
 }
Exemplo n.º 45
0
 internal FtpRenameCommand(FtpConnection connection, FtpPath source, FtpPath target)
     : base(connection, source)
 {
     Target = target;
 }
Exemplo n.º 46
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DeleCommandHandler"/> class.
 /// </summary>
 /// <param name="connection">The connection to create this command handler for</param>
 public DeleCommandHandler(FtpConnection connection)
     : base(connection, "DELE")
 {
 }
Exemplo n.º 47
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TypeCommandHandler"/> class.
 /// </summary>
 /// <param name="connection">The connection to create this command handler for</param>
 public TypeCommandHandler(FtpConnection connection)
     : base(connection, "TYPE")
 {
 }
Exemplo n.º 48
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RestCommandHandler"/> class.
 /// </summary>
 /// <param name="connection">The connection to create this command handler for</param>
 public RestCommandHandler(FtpConnection connection)
     : base(connection, "REST")
 {
 }
Exemplo n.º 49
0
 /// <summary>
 /// Initializes a new instance of the <see cref="UserCommandHandler"/> class.
 /// </summary>
 /// <param name="connection">The connection to create this command handler for</param>
 public UserCommandHandler(FtpConnection connection)
     : base(connection, "USER")
 {
 }
Exemplo n.º 50
0
 internal FtpTransportStream(FtpConnection connection) : base(connection, null)
 {
 }
Exemplo n.º 51
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RnfrCommandHandler"/> class.
 /// </summary>
 /// <param name="connection">The connection to create this command handler for</param>
 public RnfrCommandHandler(FtpConnection connection)
     : base(connection, "RNFR")
 {
 }
Exemplo n.º 52
0
 /// <summary>
 /// Initializes a new instance of the <see cref="StruCommandHandler"/> class.
 /// </summary>
 /// <param name="connection">The connection to create this command handler for</param>
 public StruCommandHandler(FtpConnection connection)
     : base(connection, "STRU")
 {
 }
Exemplo n.º 53
0
 /// <summary>
 /// Initializes a new instance of the <see cref="StruCommandHandler"/> class.
 /// </summary>
 /// <param name="connection">The connection to create this command handler for</param>
 public StruCommandHandler(FtpConnection connection)
     : base(connection, "STRU")
 {
 }
Exemplo n.º 54
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CwdCommandHandler"/> class.
 /// </summary>
 /// <param name="connection">The connection to create this command handler for</param>
 public CwdCommandHandler(FtpConnection connection)
     : base(connection, "CWD")
 {
 }
Exemplo n.º 55
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RmdCommandHandler"/> class.
 /// </summary>
 /// <param name="connection">The connection to create this command handler for</param>
 public RmdCommandHandler(FtpConnection connection)
     : base(connection, "RMD")
 {
 }
Exemplo n.º 56
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ProtCommandHandler"/> class.
 /// </summary>
 /// <param name="connection">The connection to create this command handler for</param>
 public ProtCommandHandler(FtpConnection connection)
     : base(connection, "PROT")
 {
 }
Exemplo n.º 57
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MdtmCommandHandler"/> class.
 /// </summary>
 /// <param name="connection">The connection to create this command handler for</param>
 public MdtmCommandHandler(FtpConnection connection)
     : base(connection, "MDTM")
 {
 }
Exemplo n.º 58
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AuthTlsCommandHandler"/> class.
 /// </summary>
 /// <param name="connection">The connection this instance is used for</param>
 public AuthTlsCommandHandler(FtpConnection connection)
     : base(connection, "AUTH")
 {
 }
Exemplo n.º 59
0
 /// <summary>
 /// Initializes a new instance of the <see cref="AlloCommandHandler"/> class.
 /// </summary>
 /// <param name="connection">The connection to create this command handler for</param>
 public AlloCommandHandler(FtpConnection connection)
     : base(connection, "ALLO")
 {
 }
Exemplo n.º 60
0
 /// <summary>
 /// Initializes a new instance of the <see cref="NoOpCommandHandler"/> class.
 /// </summary>
 /// <param name="connection">The connection to create this command handler for</param>
 public NoOpCommandHandler(FtpConnection connection)
     : base(connection, "NOOP")
 {
 }