コード例 #1
0
ファイル: FTPClientForm.cs プロジェクト: Edison6351/ShareX
        public FTPClientForm(FTPAccount account)
        {
            InitializeComponent();
            Icon = ShareXResources.Icon;

            lblStatus.Text = string.Empty;
            lvFTPList.SubItemEndEditing += lvFTPList_SubItemEndEditing;

            FtpTrace.AddListener(new TextBoxTraceListener(txtDebug));

            Account = account;

            Client = new FTP(account);

            pgAccount.SelectedObject = Client.Account;
            Text = "ShareX FTP client - " + account.Name;
            lblConnecting.Text = "Connecting to " + account.FTPAddress;

            TaskEx.Run(() =>
            {
                Client.Connect();
            },
            () =>
            {
                pConnecting.Visible = false;
                Refresh();
                RefreshDirectory();
            });
        }
コード例 #2
0
        /// <summary>
        /// Retrieves a file from the FTP server
        /// </summary>
        /// <param name="URI"></param>
        /// <param name="DownloadDir"></param>
        /// <param name="FileName"></param>
        static public void DownloadFile(Uri URI, string DownloadDir, string FileName)
        {
            FTP Ftp = new FTP(URI.Host, URI.Port);

            Ftp.Connect(URI.UserInfo, "");
            Ftp.ChangeDirectory(URI.AbsolutePath);
            Ftp.GetFile(FileName, DownloadDir + "\\" + FileName, true);

            Ftp.Disconnect();
        }
コード例 #3
0
        private void btnFTPTestar_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            FTP ftp = new FTP(this.edtFTP_Server.Text, Convert.ToInt32(this.edtFTP_Porta.Value), this.edtFTP_UserName.Text, this.edtFTP_Password.Text);

            try
            {
                ftp.Connect();
                if (ftp.IsConnected)
                {
                    string vCurrente = ftp.GetWorkingDirectory();

                    if (Propriedade.TipoAplicativo == TipoAplicativo.Nfe)
                    {
                        if (!ftp.changeDir(this.edtFTP_PastaDestino.Text))
                        {
                            string error = "Pasta '" + this.edtFTP_PastaDestino.Text + "' não existe no FTP.\r\nDesejá criá-la agora?";
                            if (MessageBox.Show(error, "Informação", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                            {
                                ftp.makeDir(this.edtFTP_PastaDestino.Text);
                            }
                        }
                    }

                    ftp.ChangeDir(vCurrente);

                    if (!string.IsNullOrEmpty(this.edtFTP_PastaRetornos.Text))
                    {
                        if (!ftp.changeDir(this.edtFTP_PastaRetornos.Text))
                        {
                            string error = "Pasta '" + this.edtFTP_PastaRetornos.Text + "' não existe no FTP.";
                            if (MessageBox.Show(error, "Informação", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                            {
                                ftp.makeDir(this.edtFTP_PastaRetornos.Text);
                            }
                        }
                    }

                    MessageBox.Show("FTP conectado com sucesso!", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                if (ftp.IsConnected)
                {
                    ftp.Disconnect();
                }

                Cursor = Cursors.Default;
            }
        }
コード例 #4
0
 private void buttonUpload_Click(object sender, EventArgs e)
 {
     if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
     {
         ftplib = new FTP(textBoxHost.Text, textBoxUsr.Text, textBoxPwd.Text);
         ftplib.Connect();
         new Thread(delegate()
         {
             ftplib.UploadFolderRecursively(folderBrowserDialog1.SelectedPath, ProgressEvent);
         }).Start();
     }
 }
コード例 #5
0
ファイル: FTPTest.cs プロジェクト: yuzs/donetci
        public void TestFTPUpload()
        {
            //登录
            var ftp = new FTP("hkhost6.7iit.com", "", "17dd2a829f9147");

            Assert.AreEqual(true, ftp.Connect());

            // ftp.user = "******";
            // ftp.server = "10.0.2.13";
            // ftp.pass = "******";
            Console.WriteLine(ftp.Messages);
        }
コード例 #6
0
ファイル: FTPTest.cs プロジェクト: grzpas/BandManager
        public void UploadTest()
        {
            var ftpClient = new FTP("ftp.progressband.pl", 21, "pband", "yaya2000");

            ftpClient.Connect();
            ftpClient.ChangeDir("domains/progressband.pl/public_html/modules/payroll/");
            if (ftpClient.IsConnected)
            {
                //ftpClient.OpenUpload("route.html", new MemoryStream(, false), false);
                while (ftpClient.DoUpload() > 0)
                {
                    ;
                }
            }
        }
コード例 #7
0
        private void ShowRLCServerFileViewer()
        {
            ListViewItem lvi;

            ListViewItem.ListViewSubItem lvsi;
            lstItems.Items.Clear();

            FTP clsFTP = new FTP();

            clsFTP.Connect(CONFIG.FTPIPAddress, CONFIG.FTPUsername, CONFIG.FTPPassword);
            if (CONFIG.FTPDirectory != null && CONFIG.FTPDirectory != string.Empty)
            {
                clsFTP.ChangeDirectory(CONFIG.FTPDirectory);
            }

            grpRLC.Text = "RLC File Server Management: [DOUBLE CLICK TO RELOAD] : " + CONFIG.FTPDirectory;

            try
            {
                foreach (FTP.File strFile in clsFTP.Files)
                {
                    if (strFile.ToString() != string.Empty)
                    {
                        lvi      = new ListViewItem();
                        lvi.Text = strFile.FileName;
                        //lvi.ImageIndex = 0;
                        lvi.Tag = strFile.ToString();

                        lvsi      = new ListViewItem.ListViewSubItem();
                        lvsi.Text = strFile.FileSize.ToString() + " kb";
                        lvi.SubItems.Add(lvsi);

                        lvsi      = new ListViewItem.ListViewSubItem();
                        lvsi.Text = strFile.FileDate.ToString("MM/dd/yyyy hh:mm tt");
                        lvi.SubItems.Add(lvsi);

                        lstItems.Items.Add(lvi);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error encountered while loading file list. " + Environment.NewLine + "Err #: " + ex.Message, "RetailPlus", MessageBoxButtons.OK);
            }

            clsFTP.Disconnect();
            clsFTP = null;
        }
コード例 #8
0
        /// <summary>
        /// Retrieves the listing of the files in current directory on FTP server
        /// </summary>
        /// <param name="URI"></param>
        /// <returns>The server file list as a List</returns>
        static public void ReadListing(Uri URI)
        {
            FTP Ftp = new FTP(URI.Host, URI.Port);

            ParamsHelper.AppsList = new List <string>();
            string Listing;

            Ftp.Connect(URI.UserInfo, "");

            try
            {
                Ftp.ChangeDirectory(URI.AbsolutePath);
                Listing = Ftp.GetFileList(false);
            }
            catch (Exception NewEx)
            {
                Listing = null;
                ParamsHelper.IsThreadAlive   = false;
                ParamsHelper.IsThreadError   = true;
                ParamsHelper.ThreadException = NewEx;
                return;
            }

            string[] Files = Listing.Replace("\n", "").Split('\r');

            foreach (string file in Files)
            {
                if (!String.IsNullOrEmpty(file) && file.IndexOf('.') == -1)
                {
                    ParamsHelper.AppsList.Add(file.Replace("_", " "));
                }
            }

            if (ParamsHelper.AppsList.Count == 0)
            {
                Ftp.Disconnect();
                ParamsHelper.IsThreadAlive   = false;
                ParamsHelper.IsThreadError   = true;
                ParamsHelper.ThreadException = new NetCFLibFTP.FTPException("Repository is empty");
                return;
            }

            Ftp.Disconnect();

            ParamsHelper.IsThreadAlive = false;
        }
コード例 #9
0
ファイル: FTPs.cs プロジェクト: xiongeee/BBX
        public bool TestConnect(string Serveraddress, int Serverport, string Username, string Password, int Timeout, string uploadpath, ref string message)
        {
            FTP  fTP  = new FTP(Serveraddress, Serverport, Username, Password, 1, Timeout);
            bool flag = fTP.Connect();

            if (!flag)
            {
                message = fTP.errormessage;
                return(flag);
            }
            if (!fTP.ChangeDir(uploadpath))
            {
                fTP.MakeDir(uploadpath);
                if (!fTP.ChangeDir(uploadpath))
                {
                    message += fTP.errormessage;
                    flag     = false;
                }
            }
            return(flag);
        }
コード例 #10
0
        public static bool Send(Node pTargetNode, string pFilePath)
        {
            var _fileName = Path.GetFileName(pFilePath);

            using (var _ftp = new FTP()) {
                _ftp.Host            = pTargetNode.IPAddressString;
                _ftp.Username        = pTargetNode.UserName;
                _ftp.Password        = pTargetNode.Password;
                _ftp.ConnectTimeout  = 30000;
                _ftp.ReadTimeout     = 30000;
                _ftp.TransferTimeout = 30000;
                _ftp.Passive         = false;

                var _fileNameTemp = _fileName + ".temp";

                _ftp.Connect();
                _ftp.Put(pFilePath, _fileNameTemp, false);
                _ftp.Rename(_fileNameTemp, _fileName);
                //				try { _ftp.Disconnect(true); } catch {}
            }
            return(true);
        }
コード例 #11
0
        public static void GetFile(String File)
        {
            FTP.FTPPlumbing.Timeout     = 50000;
            FTP.FTPPlumbing.PassiveMode = true;

            FTP oFTP = new FTP();

            oFTP.Connect("192.168.254.65", "alvaro", "michelle"); //mail.giftcoinc.com

            oFTP.ChangeDirectory(".");
            oFTP.Files.Download("File");
            while (!oFTP.Files.DownloadComplete)
            {
                MessageBox.Show("Uploading: TotalBytes: " + oFTP.Files.TotalBytes.ToString() + ", : PercentComplete: " + oFTP.Files.PercentComplete.ToString());
            }

            MessageBox.Show("Upload Complete: TotalBytes: " + oFTP.Files.TotalBytes.ToString() + ", : PercentComplete: " + oFTP.Files.PercentComplete.ToString());


            oFTP.Disconnect();

            return;
        }
コード例 #12
0
ファイル: FTPs.cs プロジェクト: terryxym/DiscuzNT
        /// <summary>
        /// FTP连接测试
        /// </summary>
        /// <param name="Serveraddress">FTP服务器地址</param>
        /// <param name="Serverport">FTP端口</param>
        /// <param name="Username">用户名</param>
        /// <param name="Password">密码</param>
        /// <param name="Timeout">超时时间(秒)</param>
        /// <param name="uploadpath">附件保存路径</param>
        /// <param name="message">返回信息</param>
        /// <returns>是否可用</returns>
        public bool TestConnect(string Serveraddress, int Serverport, string Username, string Password, int Timeout, string uploadpath, ref string message)
        {
            FTP  ftpupload = new FTP(Serveraddress, Serverport, Username, Password, 1, Timeout);
            bool isvalid   = ftpupload.Connect();

            if (!isvalid)
            {
                message = ftpupload.errormessage;
                return(isvalid);
            }

            //切换到指定路径下,如果目录不存在,将创建
            if (!ftpupload.ChangeDir(uploadpath))
            {
                ftpupload.MakeDir(uploadpath);
                if (!ftpupload.ChangeDir(uploadpath))
                {
                    message += ftpupload.errormessage;
                    isvalid  = false;
                }
            }
            return(isvalid);
        }
コード例 #13
0
ファイル: FTPs.cs プロジェクト: xiongeee/BBX
        public bool UpLoadFile(string path, string file, FTPUploadEnum ftpuploadname)
        {
            var fTP = new FTP();

            path = path.Replace("\\", "/");
            path = (path.StartsWith("/") ? path : ("/" + path));
            FTPConfigInfo config = null;
            bool          flag   = true;

            switch (ftpuploadname)
            {
            case FTPUploadEnum.ForumAttach:
                config = GetForumAttachInfo;
                break;

            case FTPUploadEnum.SpaceAttach:
                config = GetSpaceAttachInfo;
                break;

            case FTPUploadEnum.AlbumAttach:
                config = GetAlbumAttachInfo;
                break;

            case FTPUploadEnum.MallAttach:
                config = GetMallAttachInfo;
                break;

            case FTPUploadEnum.ForumAvatar:
                config = GetForumAvatarInfo;
                break;
            }
            fTP  = new FTP(config.Serveraddress, config.Serverport, config.Username, config.Password, 1, config.Timeout);
            path = config.Uploadpath + path;
            flag = (config.Reservelocalattach != 1);

            if (!fTP.ChangeDir(path))
            {
                string[] array = path.Split('/');
                for (int i = 0; i < array.Length; i++)
                {
                    string text = array[i];
                    if (text.Trim() != "")
                    {
                        fTP.MakeDir(text);
                        fTP.ChangeDir(text);
                    }
                }
            }
            fTP.Connect();
            if (!fTP.IsConnected)
            {
                return(false);
            }
            int num = 0;

            if (!fTP.OpenUpload(file, Path.GetFileName(file)))
            {
                fTP.Disconnect();
                return(false);
            }
            while (fTP.DoUpload() > 0L)
            {
                num = (int)(fTP.BytesTotal * 100L / fTP.FileSize);
            }
            fTP.Disconnect();
            if (flag && Utils.FileExists(file))
            {
                File.Delete(file);
            }
            return(num >= 100);
        }
コード例 #14
0
        /// <summary>
        /// TICK
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void dispatcherTimer_Tick(object sender, EventArgs e)
        {
            try
            {
                InternetConnectionState_e flags = 0;
                isConnected = InternetGetConnectedState(ref flags, 0);

                if (isConnected == false)
                {
                    return;
                }

                if (AvaliableVersions.Count == 0)
                {
                    return;
                }

                String oldLast = AvaliableVersions[AvaliableVersions.Count - 1];

                try
                {
                    ftp = new FTP("ftp.ploobs.com.br", "ploobs", "5ruTrus6");
                    ftp.Connect();
                    ftp.ChangeDir("/ploobs/Web/Updater");

                    System.Collections.ArrayList fileList = ftp.List();

                    AvaliableVersions.Clear();
                    listBox1.Items.Clear();
                    foreach (String item in fileList)
                    {
                        String[] files = item.Split(' ');
                        String   file  = files[files.Count() - 1];
                        AvaliableVersions.Add(file);
                        listBox1.Items.Add(file);
                    }
                }
                catch (Exception)
                {
                    ///do not show message box here ....
                    return;
                }
                finally
                {
                    ftp.Disconnect();
                }

                if (oldLast != AvaliableVersions[AvaliableVersions.Count - 1])
                {
                    string title = "PloobsUpdates";
                    string text  = "There is a new Version of PloobsEngine Avaliable";

                    //show balloon with built-in icon
                    this.MyNotifyIcon.ShowBalloonTip(title, text, BalloonIcon.Info);
                    this.MyNotifyIcon.TrayBalloonTipClicked += new RoutedEventHandler(MyNotifyIcon_TrayBalloonTipClicked);
                }

                if (AvaliableVersions.Count == 0)
                {
                    button1.IsEnabled = false;
                    button2.IsEnabled = false;
                }
            }
            catch (Exception)
            {
                ///nothing
            }
        }
コード例 #15
0
ファイル: ForwarderWnd.cs プロジェクト: marioricci/erp-luma
        private void ShowRLCServerFileViewer()
        {
            ListViewItem lvi;
            ListViewItem.ListViewSubItem lvsi;
            lstItems.Items.Clear();

            FTP clsFTP = new FTP();
            clsFTP.Connect(CONFIG.FTPIPAddress, CONFIG.FTPUsername, CONFIG.FTPPassword);
            if (CONFIG.FTPDirectory != null && CONFIG.FTPDirectory != string.Empty)
                clsFTP.ChangeDirectory(CONFIG.FTPDirectory);

            grpRLC.Text = "RLC File Server Management: [DOUBLE CLICK TO RELOAD] : " + CONFIG.FTPDirectory;

            try
            {
                foreach (FTP.File strFile in clsFTP.Files)
                {
                    if (strFile.ToString() != string.Empty)
                    {
                        lvi = new ListViewItem();
                        lvi.Text = strFile.FileName;
                        //lvi.ImageIndex = 0;
                        lvi.Tag = strFile.ToString();

                        lvsi = new ListViewItem.ListViewSubItem();
                        lvsi.Text = strFile.FileSize.ToString() + " kb";
                        lvi.SubItems.Add(lvsi);

                        lvsi = new ListViewItem.ListViewSubItem();
                        lvsi.Text = strFile.FileDate.ToString("MM/dd/yyyy hh:mm tt");
                        lvi.SubItems.Add(lvsi);

                        lstItems.Items.Add(lvi);
                    }
                }
            }
            catch (Exception ex) {
                MessageBox.Show("Error encountered while loading file list. " + Environment.NewLine + "Err #: " + ex.Message, "RetailPlus", MessageBoxButtons.OK);
            }

            clsFTP.Disconnect();
            clsFTP = null;
        }
コード例 #16
0
        /// <summary>
        /// Retrieves a package information from the FTP server
        /// </summary>
        /// <param name="URI"></param>
        /// <param name="AppName"></param>
        /// <returns>The file info as a string</returns>
        static public string LoadInfo(Uri URI, string AppName)
        {
            FTP    Ftp         = new FTP(URI.Host, URI.Port);
            string FileName    = AppName + ".zip";
            string InfoName    = AppName + ".info";
            string ScrShotName = AppName + ".png";
            string LogoName    = "Logo.png";
            string FileSize;
            string BufferPath = ParamsHelper.TempPath + "\\" + AppName;
            string AppInfo;

            if (!Directory.Exists(BufferPath))
            {
                Directory.CreateDirectory(BufferPath);
            }

            Ftp.Connect(URI.UserInfo, "");

            try
            {
                Ftp.ChangeDirectory(URI.AbsolutePath);
                FileSize = Ftp.GetFileSize(FileName);
                FileSize = ParamsHelper.BytesToMegs((ulong)Convert.ToInt64(FileSize)).ToString("0.###") + " МБ";
            }
            catch
            {
                FileSize = null;
            }

            try
            {
                Ftp.GetFile(InfoName, BufferPath + "\\" + InfoName, true);
                InfoName = BufferPath + "\\" + InfoName;
            }
            catch
            {
                File.Delete(BufferPath + "\\" + InfoName);
                InfoName = null;
            }

            try
            {
                Ftp.GetFile(LogoName, BufferPath + "\\" + LogoName, true);
                LogoName = BufferPath + "\\" + LogoName;
            }
            catch
            {
                File.Delete(BufferPath + "\\" + LogoName);
                LogoName = null;
            }

            try
            {
                Ftp.GetFile(ScrShotName, BufferPath + "\\" + ScrShotName, true);
                ScrShotName = BufferPath + "\\" + ScrShotName;
            }
            catch
            {
                File.Delete(BufferPath + "\\" + ScrShotName);
                ScrShotName = null;
            }

            AppInfo = FileSize + "\n" + InfoName + "\n" + LogoName + "\n" + ScrShotName;

            Ftp.Disconnect();

            return(AppInfo);
        }
コード例 #17
0
        public static void TestFTPAccount(FTPAccount account)
        {
            string msg = string.Empty;
            string remotePath = account.GetSubFolderPath();
            List<string> directories = new List<string>();

            try
            {
                if (account.Protocol == FTPProtocol.FTP || account.Protocol == FTPProtocol.FTPS)
                {
                    using (FTP ftp = new FTP(account))
                    {
                        if (ftp.Connect())
                        {
                            if (!ftp.DirectoryExists(remotePath))
                            {
                                directories = ftp.CreateMultiDirectory(remotePath);
                            }

                            if (ftp.IsConnected)
                            {
                                if (directories.Count > 0)
                                {
                                    msg = "Connected!\r\nCreated folders:\r\n" + string.Join("\r\n", directories);
                                }
                                else
                                {
                                    msg = "Connected!";
                                }
                            }
                        }
                    }
                }
                else if (account.Protocol == FTPProtocol.SFTP)
                {
                    using (SFTP sftp = new SFTP(account))
                    {
                        if (sftp.Connect())
                        {
                            if (!sftp.DirectoryExists(remotePath))
                            {
                                directories = sftp.CreateMultiDirectory(remotePath);
                            }

                            if (sftp.IsConnected)
                            {
                                if (directories.Count > 0)
                                {
                                    msg = "Connected!\r\nCreated folders:\r\n" + string.Join("\r\n", directories);
                                }
                                else
                                {
                                    msg = "Connected!";
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                msg = e.Message;
            }

            MessageBox.Show(msg, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
コード例 #18
0
        private void btnTestarFTP_Click(object sender, EventArgs e)
        {
            this.ErrorFtp = false;
            FTP ftp = null;

            try
            {
                ftp = new FTP(this.edtFTP_Server.Text, Convert.ToInt32("0" + this.edtFTP_Porta.Text), this.edtFTP_UserName.Text, this.edtFTP_Password.Text);
                ftp.Connect();
                if (ftp.IsConnected)
                {
                    string vCurrente = ftp.GetWorkingDirectory();

                    const string error = "Pasta {0} '{1}' não existe no FTP.\r\nDeseja criá-la agora?";

                    if (!ftp.changeDir(edtFTP_PastaDestino.Text))
                    {
                        if (MetroFramework.MetroMessageBox.Show(uninfeDummy.mainForm, string.Format(error, "destino", this.edtFTP_PastaDestino.Text), "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            ftp.makeDir(this.edtFTP_PastaDestino.Text);
                            if (!ftp.changeDir(this.edtFTP_PastaDestino.Text))
                            {
                                throw new Exception("Pasta de destino criada mas não foi possivel acessá-la");
                            }
                        }
                        else
                        {
                            ErrorFtp = true;
                        }
                    }

                    ftp.ChangeDir(vCurrente);

                    if (!string.IsNullOrEmpty(this.edtFTP_PastaRetornos.Text))
                    {
                        if (!ftp.changeDir(this.edtFTP_PastaRetornos.Text))
                        {
                            if (MetroFramework.MetroMessageBox.Show(uninfeDummy.mainForm, string.Format(error, "para retornos", this.edtFTP_PastaRetornos.Text), "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                            {
                                ftp.makeDir(this.edtFTP_PastaRetornos.Text);
                                if (!ftp.changeDir(this.edtFTP_PastaRetornos.Text))
                                {
                                    throw new Exception("Pasta de retornos criada mas não foi possivel acessá-la");
                                }
                            }
                            else
                            {
                                this.ErrorFtp = true;
                            }
                        }
                    }

                    MetroFramework.MetroMessageBox.Show(uninfeDummy.mainForm, "FTP conectado com sucesso," + (ErrorFtp ? "\r\nmas houve erro da definição da(s) pasta(s)" : ""), "");
                }
                else
                {
                    throw new Exception("FTP não conectado");
                }
            }
            catch (Exception ex)
            {
                this.ErrorFtp = true;
                MetroFramework.MetroMessageBox.Show(uninfeDummy.mainForm, ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                if (ftp != null)
                {
                    if (ftp.IsConnected)
                    {
                        ftp.Disconnect();
                    }
                }
            }
        }
コード例 #19
0
 protected void _Connect()
 {
     _Ftp.Connect(this.Host, this.Port, this.Username, this.Password);
     _Ftp.timeout = this.timeout;
     RootPath     = _Ftp.GetWorkingDirectory();
 }
コード例 #20
0
ファイル: FTPs.cs プロジェクト: terryxym/DiscuzNT
        /// <summary>
        /// 上传远程附件
        /// </summary>
        /// <param name="path">要上传的文件路径(网络地址)</param>
        /// <param name="file">要上传的文件(本地地址)</param>
        /// <param name="ftpuploadname">远程FTP类型(论坛,空间或相册)</param>
        /// <returns>是否成功</returns>
        public bool UpLoadFile(string path, string file, FTPUploadEnum ftpuploadname)
        {
            FTP ftpupload = new FTP();

            //转换路径分割符为"/"
            path = path.Replace("\\", "/");
            path = path.StartsWith("/") ? path : "/" + path;

            //删除file参数文件
            bool delfile = true;

            //根据上传名称确定上传的FTP服务器
            switch (ftpuploadname)
            {
            //论坛附件
            case FTPUploadEnum.ForumAttach:
            {
                ftpupload = new FTP(GetForumAttachInfo.Serveraddress, GetForumAttachInfo.Serverport, GetForumAttachInfo.Username, GetForumAttachInfo.Password, 1, GetForumAttachInfo.Timeout);
                path      = GetForumAttachInfo.Uploadpath + path;
                delfile   = (GetForumAttachInfo.Reservelocalattach == 1) ? false : true;
                break;
            }

            //空间附件
            case FTPUploadEnum.SpaceAttach:
            {
                ftpupload = new FTP(GetSpaceAttachInfo.Serveraddress, GetSpaceAttachInfo.Serverport, GetSpaceAttachInfo.Username, GetSpaceAttachInfo.Password, 1, GetSpaceAttachInfo.Timeout);
                path      = GetSpaceAttachInfo.Uploadpath + path;
                delfile   = (GetSpaceAttachInfo.Reservelocalattach == 1) ? false : true;
                break;
            }

            //相册附件
            case FTPUploadEnum.AlbumAttach:
            {
                ftpupload = new FTP(GetAlbumAttachInfo.Serveraddress, GetAlbumAttachInfo.Serverport, GetAlbumAttachInfo.Username, GetAlbumAttachInfo.Password, 1, GetAlbumAttachInfo.Timeout);
                path      = GetAlbumAttachInfo.Uploadpath + path;
                delfile   = (GetAlbumAttachInfo.Reservelocalattach == 1) ? false : true;
                break;
            }

            //商城附件
            case FTPUploadEnum.MallAttach:
            {
                ftpupload = new FTP(GetMallAttachInfo.Serveraddress, GetMallAttachInfo.Serverport, GetMallAttachInfo.Username, GetMallAttachInfo.Password, 1, GetMallAttachInfo.Timeout);
                path      = GetMallAttachInfo.Uploadpath + path;
                delfile   = (GetMallAttachInfo.Reservelocalattach == 1) ? false : true;
                break;
            }

            //论坛头像
            case FTPUploadEnum.ForumAvatar:
            {
                ftpupload = new FTP(GetForumAvatarInfo.Serveraddress, GetForumAvatarInfo.Serverport, GetForumAvatarInfo.Username, GetForumAvatarInfo.Password, 1, GetForumAvatarInfo.Timeout);
                path      = GetForumAvatarInfo.Uploadpath + path;
                delfile   = (GetForumAvatarInfo.Reservelocalattach == 1) ? false : true;
                break;
            }
            }

            //切换到指定路径下,如果目录不存在,将创建
            if (!ftpupload.ChangeDir(path))
            {
                foreach (string pathstr in path.Split('/'))
                {
                    if (pathstr.Trim() != "")
                    {
                        ftpupload.MakeDir(pathstr);
                        ftpupload.ChangeDir(pathstr);
                    }
                }
            }

            ftpupload.Connect();

            if (!ftpupload.IsConnected)
            {
                return(false);
            }

            int perc = 0;

            //绑定要上传的文件
            if (!ftpupload.OpenUpload(file, System.IO.Path.GetFileName(file)))
            {
                ftpupload.Disconnect();
                return(false);
            }
            //Stopwatch sw = new Stopwatch();
            //sw.Start();

            //开始进行上传
            while (ftpupload.DoUpload() > 0)
            {
                perc = (int)(((ftpupload.BytesTotal) * 100) / ftpupload.FileSize);
            }

            ftpupload.Disconnect();

            //long elapse = sw.ElapsedMilliseconds;
            //sw.Stop();

            //(如存在)删除指定目录下的文件
            if (delfile && Utils.FileExists(file))
            {
                System.IO.File.Delete(file);
            }

            return((perc >= 100) ? true : false);
        }
コード例 #21
0
        private void FTPTestAccount(FTPAccount account)
        {
            string        msg         = "";
            string        remotePath  = account.GetSubFolderPath();
            List <string> directories = new List <string>();

            try
            {
                if (account.Protocol == FTPProtocol.FTP || account.Protocol == FTPProtocol.FTPS)
                {
                    using (FTP ftp = new FTP(account))
                    {
                        if (ftp.Connect())
                        {
                            if (!ftp.DirectoryExists(remotePath))
                            {
                                directories = ftp.CreateMultiDirectory(remotePath);
                            }

                            if (ftp.IsConnected)
                            {
                                if (directories.Count > 0)
                                {
                                    msg = Resources.UploadersConfigForm_TestFTPAccount_Connected_Created_folders + "\r\n" + string.Join("\r\n", directories);
                                }
                                else
                                {
                                    msg = Resources.UploadersConfigForm_TestFTPAccount_Connected_;
                                }
                            }
                        }
                    }
                }
                else if (account.Protocol == FTPProtocol.SFTP)
                {
                    using (SFTP sftp = new SFTP(account))
                    {
                        if (sftp.Connect())
                        {
                            if (!sftp.DirectoryExists(remotePath))
                            {
                                directories = sftp.CreateMultiDirectory(remotePath);
                            }

                            if (sftp.IsConnected)
                            {
                                if (directories.Count > 0)
                                {
                                    msg = Resources.UploadersConfigForm_TestFTPAccount_Connected_Created_folders + "\r\n" + string.Join("\r\n", directories);
                                }
                                else
                                {
                                    msg = Resources.UploadersConfigForm_TestFTPAccount_Connected_;
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                msg = e.Message;
            }

            MessageBox.Show(msg, "ShareX", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
コード例 #22
0
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            isDownloading = true;
            this.remove.Dispatcher.BeginInvoke(DispatcherPriority.Send,
                                               (Action)(() => { remove.IsEnabled = false; }));
            HandleXnaVersion();

            if (isConnected == false)
            {
                MessageBox.Show("No Internet Connection");
                return;
            }

            try
            {
                String sitem = listBox1.SelectedItem as String;
                if (String.IsNullOrEmpty(sitem))
                {
                    MessageBox.Show("You Must select a version");
                    this.remove.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                                                       (Action)(() => { remove.IsEnabled = true; }));
                    isDownloading = false;
                    return;
                }
                if (sitem != packageName)
                {
                    if (!String.IsNullOrEmpty(packageName))
                    {
                        DeleteCurrentEngineVersion();
                        GetVersionOnRegistry();
                        if (!String.IsNullOrEmpty(packageName))
                        {
                            MessageBox.Show("You need to unistall current version to be able to install another");
                            this.remove.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                                                               (Action)(() => { remove.IsEnabled = true; }));
                            isDownloading = false;
                            return;
                        }
                    }
                    Random rd    = new Random();
                    int    rdnum = rd.Next();

                    button1.IsEnabled  = false;
                    progressBar1.Value = 0;

                    label2.Content = "Downloading";
                    Task.Factory.StartNew(() =>
                    {
                        try
                        {
                            FTP ftp = new FTP("ftp.ploobs.com.br", "ploobs", "5ruTrus6");
                            ftp.Connect();
                            ftp.ChangeDir("/ploobs/Web/Updater/" + sitem);
                            String temppath = System.IO.Path.GetTempPath() + System.IO.Path.GetRandomFileName();
                            ftp.OpenDownload("PloobsEngine.rar", temppath, true);


                            while (ftp.DoDownload() != 0)
                            {
                                progressBar1.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                                                                    (Action)(() => { progressBar1.Value = 100 * (float)ftp.BytesTotal / (float)ftp.FileSize; }));
                            }

                            label2.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                                                          (Action)(() => { label2.Content = "INSTALLING"; }));


                            if (File.Exists(System.IO.Path.GetTempPath() + "PloobsEngine//setup.exe"))
                            {
                                File.Delete(System.IO.Path.GetTempPath() + "PloobsEngine//setup.exe");
                            }

                            if (Directory.Exists(System.IO.Path.GetTempPath() + "PloobsEngine/"))
                            {
                                Directory.Delete(System.IO.Path.GetTempPath() + "PloobsEngine/", true);
                            }

                            RarArchive.WriteToDirectory(temppath, System.IO.Path.GetTempPath(), NUnrar.Common.ExtractOptions.ExtractFullPath);

                            temppath = System.IO.Path.GetTempPath() + "PloobsEngine//setup.exe";

                            System.Diagnostics.Process process = new System.Diagnostics.Process();
                            process.StartInfo.FileName         = temppath;
                            process.Start();
                            process.WaitForExit();

                            packageName = sitem;
                            GetVersionOnRegistry();

                            label2.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                                                          (Action)(() => { label2.Content = "Current Version: " + packageName; }));


                            MySqlCommonConnection.WriteClientToDB(sitem);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.ToString());
                            label2.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                                                          (Action)(() => { label2.Content = "ERROR"; }));
                        }
                        finally
                        {
                            button1.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                                                           (Action)(() => { button1.IsEnabled = true; }));

                            if (packageName != null)
                            {
                                label2.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                                                              (Action)(() => { label2.Content = "CurrentVersion: " + packageName; }));
                            }
                        }
                    }
                                          );
                }
                else
                {
                    MessageBox.Show("You already have this version installed, Unistall it first clicking on Remove Current Version");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

            isDownloading = false;
            this.remove.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
                                               (Action)(() => { remove.IsEnabled = true; }));
        }
コード例 #23
0
ファイル: Empresa.cs プロジェクト: matBatista/uninfe
        /// <summary>
        /// Copia o arquivo para o FTP
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="folderName"></param>
        public void SendFileToFTP(string fileName, string folderName)
        {
            //verifique se o arquivo existe e se o FTP da empresa está configurado e ativo
            if (File.Exists(fileName) && this.FTPIsAlive)
            {
                Thread t = new Thread(new ThreadStart(delegate()
                {
                    string arqDestino = Path.Combine(Path.GetTempPath(), Path.GetFileName(fileName));
                    //Copia o arquivo para a pasta temp
                    FileInfo oArquivo = new FileInfo(fileName);
                    oArquivo.CopyTo(arqDestino, true);

                    FTP ftp = new FTP(this.FTPNomeDoServidor, this.FTPPorta, this.FTPNomeDoUsuario, this.FTPSenha);
                    try
                    {
                        //conecta ao ftp
                        ftp.Connect();
                        if (!ftp.IsConnected)
                        {
                            throw new Exception("FTP '" + this.FTPNomeDoServidor + "' não conectado");
                        }

                        ftp.PassiveMode = this.FTPPassivo;

                        //pega a pasta corrente no ftp
                        string vCorrente = ftp.GetWorkingDirectory();

                        //tenta mudar para a pasta de destino
                        if (!ftp.changeDir(folderName))
                        {
                            //como nao foi possivel mudar de pasta, a cria
                            ftp.makeDir(folderName);
                            if (!ftp.changeDir(folderName))
                            {
                                throw new Exception("Pasta '" + folderName + "' criada, mas não foi possível acessá-la");
                            }
                        }
                        //volta para a pasta corrente já que na "makeDir" a pasta se torna ativa na ultima pasta criada
                        ftp.ChangeDir(vCorrente);

                        //transfere o arquivo da pasta temp
                        string remote_filename = folderName + "/" + Path.GetFileName(fileName);
                        ftp.UploadFile(arqDestino, remote_filename, false);

                        if (ftp.GetFileSize(remote_filename) == 0)
                        {
                            throw new Exception("Arquivo '" + remote_filename + "' não encontrado no FTP");
                        }

                        Auxiliar.WriteLog("Arquivo '" + fileName + "' enviado ao FTP com o nome '" + remote_filename + "' com sucesso.", false);
                    }
                    catch (Exception ex)
                    {
                        Auxiliar.WriteLog("Ocorreu um erro ao tentar conectar no FTP: " + ex.Message, false);
                        ///
                        /// gravado o log de ftp aqui, pq o 'chamador' nao o trataria
                        ///
                        new Auxiliar().GravarArqErroERP(Path.ChangeExtension(fileName, ".ftp"), ex.Message);
                    }
                    finally
                    {
                        if (ftp.IsConnected)
                        {
                            ftp.Disconnect();
                        }

                        //exclui o arquivo transferido da pasta temporaria
                        Functions.DeletarArquivo(arqDestino);
                    }
                    doneThread_FTP(Thread.CurrentThread);
                }));
                this.threads.Add(t);
                t.IsBackground = true;
                //t.Name = name;
                t.Start();
                t.Join();
            }
        }