Exemplo n.º 1
0
        private void BtnDisconnectClick(object sender, EventArgs e)
        {
            SetButtonsEnabledDisabled(false);

            _ftp.Close();
            _ftp = null;
        }
Exemplo n.º 2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        /// <param name="filedownloadname"></param>
        /// <param name="dir"></param>
        /// <returns></returns>
        public string FtpStream(HttpContext context, string filedownloadname, string dir)
        {
            string        stream = string.Empty;
            FtpConnection ftp    = this.FtpConn();

            ftp.SetCurrentDirectory(dir);

            //ftp.

            try
            {
                if (ftp.FileExist(filedownloadname))
                {
                    FtpStream ftpfs = ftp.OpenFile(filedownloadname, GenericRights.Read);

                    stream = "<";
                    StreamReader reader = new StreamReader(ftpfs);

                    while (reader.Read() > 0)
                    {
                        stream += reader.ReadToEnd();
                    }
                }
                else
                {
                    context.Response.Write("<script>alert('file does not exist!');</script>");
                }
            }
            finally
            {
                ftp.Close();
            }
            return(stream);
        }
 private void Disconnect()
 {
     //Close and dispose the ftp connection
     _Connection.Close();
     _Connection.Dispose();
     _Connection = null;
 }
Exemplo n.º 4
0
 public void close()
 {
     if (conn != null)
     {
         conn.Close();
     }
 }
Exemplo n.º 5
0
        private bool _Reconnect()
        {
            try
            {
                if (_ftpSession != null)
                {
                    _ftpSession.Close();
                    _ftpSession.Dispose();
                    _ftpSession = null;
                    GC.Collect();
                }

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

            return(false);
        }
Exemplo n.º 6
0
 private void DownFiles(FtpConnection connection)
 {
     try
     {
         connection.ChDir("PDA");
         string[] files = connection.GetFiles();
         if (null != files && files.Length > 0)
         {
             var app_dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
             for (int i = 0; i < files.Length; i++)
             {
                 connection.DownloadFile(files[i], app_dir + "\\" + files[i]);
             }
             Console.WriteLine("download complete");
         }
         else
         {
             Console.WriteLine("the directory has any file");
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message);
     }
     finally
     {
         connection.Close();
     }
 }
Exemplo n.º 7
0
        public static List <string> GetFileList(string ftpServerName, int ftpPortNumber, string ftpServerUserName, string ftpServerPassWord, string folder, DateTime ReadDate)
        {
            var results = new List <string>();

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

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

            var files = new FtpFileInfo[0];

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

            files = ftp.GetFiles();

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

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

            ftp.Close();
            return(results);
        }
    public void Connect(FTPCredentials credentials, Process process, SupplierSettingClass settings)
    {
        var ftp = new FtpConnection(credentials.Host, credentials.Username, credentials.Password);

        ftp.Open();
        ftp.Login();
        DoSomething(settings);
        ftp.Close();
    }
Exemplo n.º 9
0
        public static FtpFileInfo[] GetFiles(string path)
        {
            FtpConnection conn = GetFtpConnection();

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

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

            ClearFtp(ftp, "/");

            ftp.Close();
        }
Exemplo n.º 11
0
        private void ClearFtp()
        {
            var ftp = new FtpConnection(_ftpTestAccount.Server, _ftpTestAccount.UserName, _ftpTestAccount.Password);

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

            ClearFtp(ftp, "/");

            ftp.Close();
        }
Exemplo n.º 12
0
        public static FtpDirectoryInfo[] GetDirectories(string path)
        {
            FtpConnection conn = GetFtpConnection();

            conn.Open();
            conn.Login();
            FtpDirectoryInfo[] exists = conn.GetDirectories(path);
            conn.Close();
            conn.Dispose();
            return(exists);
        }
Exemplo n.º 13
0
        public static bool DirectoryExists(string path)
        {
            FtpConnection conn = GetFtpConnection();

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

            conn.Close();
            conn.Dispose();
            return(exists);
        }
Exemplo n.º 14
0
 /// <summary>
 ///
 /// </summary>
 public void quit()
 {
     logger.pushOperation("FTP.disconnect");
     try
     {
         sFTP.Close();
     }
     catch (Exception e)
     {
         logger.log("Erro ao conectar FTP: " + e.Message, Logger.LogType.ERROR, e, false);
     }
     finally
     {
         logger.releaseOperation();
     }
 }
Exemplo n.º 15
0
        /// <summary>
        ///	删除文件
        /// </summary>
        /// <param name="fileName"></param>
        public void DeleteFile(string fileName)
        {
            FtpConnection ftp = this.FtpConn();

            try
            {
                ftp.DeleteFile(fileName);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                ftp.Close();
            }
        }
Exemplo n.º 16
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.º 17
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.º 18
0
        //main operations
        //download .pdf and print
        private void ftpOperations()
        {
            Int64 fileSize    = 0;
            bool  fileProblem = false;

            using (FtpConnection ftp = new FtpConnection(server.Text, login.Text, password.Text))
            {
                try
                {
                    ftp.Open();
                    loggingBox.Invoke(new Action(delegate()
                    {
                        loggingBox.Items.Add("Nawiązuję połączenie...");
                    }));
                    saveToFile();
                    //connect to ftp and set remote and local directory
                    ftp.Login();
                    ftp.SetCurrentDirectory("//" + packingStationNumber);
                    ftp.SetLocalDirectory("C:\\tmp");
                }
                catch (ThreadAbortException) { }
                catch (Exception e)
                {
                    loggingBox.Invoke(new Action(delegate()
                    {
                        loggingBox.Items.Add("Błąd połączenia " + e);
                    }));
                    saveToFile();
                    btnStart.Invoke(new Action(delegate()
                    {
                        btnStart.Enabled = true;
                    }));
                    btnStop.Invoke(new Action(delegate()
                    {
                        btnStop.Enabled = false;
                    }));
                    startOperations.Abort();
                }
                while (true)
                {
                    btnStart.Invoke(new Action(delegate()
                    {
                        if (btnStart.Enabled == true)
                        {
                            btnStart.Enabled = false;
                        }
                    }));
                    loggingBox.Invoke(new Action(delegate()
                    {
                        if (loggingBox.Items.Count > 2000)
                        {
                            loggingBox.Items.Clear();
                        }
                    }));
                    try
                    {
                        //search file on ftp
                        foreach (var file in ftp.GetFiles())
                        {
                            loggingBox.Invoke(new Action(delegate()
                            {
                                loggingBox.Items.Add("Pobieram plik " + file.Name);
                            }));
                            saveToFile();
                            foreach (var pdfFile in Directory.GetFiles("C:\\tmp"))
                            {
                                if (pdfFile == "C:\\tmp\\" + file.Name)
                                {
                                    loggingBox.Invoke(new Action(delegate()
                                    {
                                        loggingBox.Items.Add("Znalazłem dubla: " + file.Name);
                                    }));
                                    saveToFile();
                                    fileSize    = new FileInfo("C:\\tmp\\" + file.Name).Length;
                                    fileProblem = true;
                                }
                            }
                            if (!fileProblem)
                            {
                                ftp.GetFile(file.Name, false);
                            }

                            else if (fileSize > 40000)
                            {
                                MessageBox.Show("Twoja etykieta została pobrana już wcześniej i prawdopodobnie została wysłana. Jej nazwa to " + file.Name, "WARRNING", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                                loggingBox.Invoke(new Action(delegate()
                                {
                                    loggingBox.Items.Add("Etykieta już jest na dysku: " + file.Name);
                                }));
                                saveToFile();
                                fileProblem = true;
                            }
                            else if (fileSize < 40000)
                            {
                                File.Delete("C:\\tmp\\" + file.Name);
                                ftp.GetFile(file.Name, false);
                                loggingBox.Invoke(new Action(delegate()
                                {
                                    loggingBox.Items.Add("Etykieta w tmp ma zbyt mały rozmiar: " + file.Name + " i została znowu pobrana");
                                }));
                                saveToFile();
                                fileProblem = false;
                            }
                            ftp.RemoveFile(file.Name);
                            if (!fileProblem)
                            {
                                //run program to print .pdf
                                if (sumatra_checkbox.Checked == false)
                                {
                                    System.Diagnostics.Process          process   = new System.Diagnostics.Process();
                                    System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                                    FindProgram pdfProgramName = new FindProgram();
                                    startInfo.FileName  = (pdfProgramName.findPDFprogram("Adobe") + "\\Reader 11.0\\Reader\\AcroRd32.exe");
                                    startInfo.Arguments = "/s /o /t C:\\tmp\\" + file.Name + " " + printer.Text;
                                    process.StartInfo   = startInfo;
                                    loggingBox.Invoke(new Action(delegate()
                                    {
                                        loggingBox.Items.Add("Otwieram AR i wywołuję wydruk...");
                                    }));
                                    saveToFile();
                                    process.Start();
                                    Thread.Sleep(4000);
                                    process.Close();
                                }
                                else
                                {
                                    System.Diagnostics.Process          process   = new System.Diagnostics.Process();
                                    System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
                                    FindProgram pdfProgramName = new FindProgram();
                                    startInfo.FileName  = (pdfProgramName.findPDFprogram("SumatraPDF") + "\\SumatraPDF.exe");
                                    startInfo.Arguments = "-silent C:\\tmp\\" + file.Name + " -print-settings fit -print-to " + printer.Text + " -exit-when-done";
                                    process.StartInfo   = startInfo;
                                    loggingBox.Invoke(new Action(delegate()
                                    {
                                        loggingBox.Items.Add("Otwieram SumatraPDF i wywołuję wydruk...");
                                    }));
                                    saveToFile();
                                    process.Start();
                                    Thread.Sleep(2000);
                                    process.Close();
                                }
                            }
                            fileProblem = false;
                        }
                    }
                    catch (ThreadAbortException) { }
                    catch (Exception e)
                    {
                        loggingBox.Invoke(new Action(delegate()
                        {
                            loggingBox.Items.Add("Błąd przetwarzania plików " + e);
                        }));
                        saveToFile();
                        loggingBox.Invoke(new Action(delegate()
                        {
                            loggingBox.Items.Add("Ponowne nawiązanie połączenia");
                        }));
                        ftp.Close();
                        ftp.Open();
                        ftp.Login();
                        ftp.SetCurrentDirectory("/" + packingStationNumber);
                        ftp.SetLocalDirectory("C:\\tmp");
                        continue;
                    }
                    Thread.Sleep(750);
                    loggingBox.Invoke(new Action(delegate()
                    {
                        loggingBox.Items.Add("[...]");
                    }));

                    loggingBox.Invoke(new Action(delegate()
                    {
                        loggingBox.TopIndex = loggingBox.Items.Count - 1;
                    }));
                }
            }
        }
Exemplo n.º 19
0
        private ActionResult FtpUpload(IJob job)
        {
            var actionResult = Check(job.Profile);

            if (!actionResult)
            {
                Logger.Error("Canceled FTP upload action.");
                return(actionResult);
            }

            if (string.IsNullOrEmpty(job.Passwords.FtpPassword))
            {
                Logger.Error("No ftp password specified in action");
                return(new ActionResult(ActionId, 102));
            }

            Logger.Debug("Creating ftp connection.\r\nServer: " + job.Profile.Ftp.Server + "\r\nUsername: "******"Can not connect to the internet for login to ftp. Win32Exception Message:\r\n" +
                                 ex.Message);
                    ftp.Close();
                    return(new ActionResult(ActionId, 108));
                }

                Logger.Error("Win32Exception while login to ftp server:\r\n" + ex.Message);
                ftp.Close();
                return(new ActionResult(ActionId, 104));
            }
            catch (Exception ex)
            {
                Logger.Error("Exception while login to ftp server:\r\n" + ex.Message);
                ftp.Close();
                return(new ActionResult(ActionId, 104));
            }

            var fullDirectory = job.TokenReplacer.ReplaceTokens(job.Profile.Ftp.Directory).Trim();

            if (!IsValidPath(fullDirectory))
            {
                Logger.Warn("Directory contains invalid characters \"" + fullDirectory + "\"");
                fullDirectory = MakeValidPath(fullDirectory);
            }

            Logger.Debug("Directory on ftp server: " + fullDirectory);

            var directories = fullDirectory.Split(new[] { "/" }, StringSplitOptions.RemoveEmptyEntries);

            try
            {
                foreach (var directory in directories)
                {
                    if (!ftp.DirectoryExists(directory))
                    {
                        Logger.Debug("Create folder: " + directory);
                        ftp.CreateDirectory(directory);
                    }

                    Logger.Debug("Move to: " + directory);
                    ftp.SetCurrentDirectory(directory);
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Exception while setting directory on ftp server\r\n:" + ex.Message);
                ftp.Close();
                return(new ActionResult(ActionId, 105));
            }

            var addendum = "";

            if (job.Profile.Ftp.EnsureUniqueFilenames)
            {
                Logger.Debug("Generate addendum for unique filename");
                try
                {
                    addendum = AddendumForUniqueFilename(Path.GetFileName(job.OutputFiles[0]), ftp);
                    Logger.Debug("The addendum for unique filename is \"" + addendum +
                                 "\" If empty, the file was already unique.");
                }
                catch (Exception ex)
                {
                    Logger.Error("Exception while generating unique filename\r\n:" + ex.Message);
                    ftp.Close();
                    return(new ActionResult(ActionId, 106));
                }
            }

            foreach (var file in job.OutputFiles)
            {
                try
                {
                    var targetFile = Path.GetFileNameWithoutExtension(file) + addendum + Path.GetExtension(file);
                    ftp.PutFile(file, MakeValidPath(targetFile));
                }
                catch (Exception ex)
                {
                    Logger.Error("Exception while uploading the file \"" + file + "\": \r\n" + ex.Message);
                    ftp.Close();
                    return(new ActionResult(ActionId, 107));
                }
            }

            ftp.Close();
            return(new ActionResult());
        }
Exemplo n.º 20
0
 public void Close()
 {
     _ftpConnection.Close();
 }
Exemplo n.º 21
0
        /// <summary>
        /// 通过Ftp拷贝外网的文件
        /// </summary>
        /// <param name="Psa_attachname">文件的名称</param>
        /// <param name="Psa_file_Size">文件的字节数</param>
        /// <param name="AttachPath">存放文件的路径[~/AffAirDirInfo/20080202/082600043/]~为服务器的物理路径</param>
        /// <param name="oYearDim"></param>
        /// <returns>拷贝文件是否成功</returns>
        public bool CopyFile(string Psa_attachname, int Psa_file_Size, string AttachPath, string oYearDim)
        {
            bool isPass = false;

            if (Psa_attachname == string.Empty || Psa_file_Size < 0)
            {
                return(false);
            }
            try
            {
                using (FtpConnection ftp = this.FtpConn())
                {
                    byte[] bytes = new byte[Psa_file_Size];
                    //string oProcEventAttachPath = GetProcEventAttachPath();
                    string oProcEventAttachPath = oYearDim + "/";
                    string fileUrl = oProcEventAttachPath + Psa_attachname;
                    //ftp.SetCurrentDirectory("/");
                    if (ftp.FileExist(fileUrl))
                    {
                        try
                        {
                            //ftp.SetCurrentDirectory(oProcEventAttachPath);
                            FtpStream ftpfs = ftp.OpenFile(fileUrl, GenericRights.Read);

                            //FtpStream ftpfs=ftp.OpenFile(Psa_attachname,GenericRights.Read);

                            Stream     oRtream = (Stream)ftpfs;
                            FileStream fs      = new FileStream(AttachPath + Psa_attachname, FileMode.Create, FileAccess.Write);
                            //int index = oRtream.Read(bytes,0,Psa_file_Size);
                            int count = oRtream.Read(bytes, 0, 10240);

                            //						HttpWebRequest webRequest = (HttpWebRequest) WebRequest.Create("http://211.144.95.130/pdhb.synadminweb/AffAirDirInfo/"+fileUrl);
                            //						HttpWebResponse webResponse = (HttpWebResponse) webRequest.GetResponse();
                            //						Stream oRtream = webResponse.GetResponseStream();
                            //						//int index = oRtream.Read(bytes,0,Psa_file_Size);
                            //						FileStream fs = new FileStream(AttachPath + Psa_attachname, FileMode.Create, FileAccess.Write);
                            //						int count = oRtream.Read( bytes, 0, 1024 );
                            fs.Write(bytes, 0, count);
                            while (count > 0)
                            {
                                // Dump the 256 characters on a string and display the string onto the console.

                                count = oRtream.Read(bytes, 0, 10240);
                                fs.Write(bytes, 0, count);
                            }


                            oRtream.Close();
                            //						webResponse.Close();



                            fs.Flush();
                            fs.Close();



                            isPass = true;
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("FTP读取文件失败原因:" + ex.Message);
                        }
                    }
//					else
//					{
//						throw new Exception("文件不存在!");
//					}
                }
            }
            catch (Exception ex)
            {
                throw new Exception("保存文件信息失败!请查看Ftp连接是否成功!原因:" + ex.Message, ex);
            }
            finally
            {
                ftp.Close();
            }

            return(isPass);
        }