コード例 #1
1
ファイル: FtpTests.cs プロジェクト: talanc/FtpServerTest
        public void VerifyListing(string host, string username, string password)
        {
            var ftpClient = new FtpClient();

            ftpClient.Host = host;
            ftpClient.Credentials = new NetworkCredential(username, password);
            ftpClient.Connect();
            var listing = ftpClient.GetListing();
            Assert.IsNotNull(listing);
        }
コード例 #2
0
        /// <summary>
        /// Example illustrating how to dereference a symbolic link
        /// in a file listing. You can also pass the FtpListOption.DerefLinks
        /// flag to GetListing() to have automatically done in which
        /// case the FtpListItem.LinkObject property will contain the
        /// FtpListItem representing the object the link points at. The
        /// LinkObject property will be null if there was a problem resolving
        /// the target.
        /// </summary>
        public static void DereferenceLinkExample() {
            using (FtpClient client = new FtpClient()) {
                client.Credentials = new NetworkCredential("user", "pass");
                client.Host = "somehost";

                // This propety controls the depth of recursion that
                // can be done before giving up on resolving the link.
                // You can set the value to -1 for infinite depth 
                // however you are strongly discourage from doing so.
                // The default value is 20, the following line is
                // only to illustrate the existance of the property.
                // It's also possible to override this value as one
                // of the overloaded arguments to the DereferenceLink() method.
                client.MaximumDereferenceCount = 20;

                // Notice the FtpListOption.ForceList flag being passed. This is because
                // symbolic links are only supported in UNIX style listings. My personal
                // experience has been that in practice MLSD listings don't specify an object
                // as a link, but rather list the link as a regular file or directory
                // accordingly. This may not always be the case however that's what I've
                // observed over the life of this project so if you run across the contrary
                // please report it. The specification for MLSD does include links so it's
                // possible some FTP server implementations do include links in the MLSD listing.
                foreach (FtpListItem item in client.GetListing(null, FtpListOption.ForceList | FtpListOption.Modify)) {
                    Console.WriteLine(item);

                    // If you call DerefenceLink() on a FtpListItem.Type other
                    // than Link a FtpException will be thrown. If you call the
                    // method and the LinkTarget is null a FtpException will also
                    // be thrown.
                    if (item.Type == FtpFileSystemObjectType.Link && item.LinkTarget != null) {
                        item.LinkObject = client.DereferenceLink(item);

                        // The return value of DerefenceLink() will be null
                        // if there was a problem.
                        if (item.LinkObject != null) {
                            Console.WriteLine(item.LinkObject);
                        }
                    }
                }

                // This example is similar except it uses the FtpListOption.DerefLinks
                // flag to have symbolic links automatically resolved. You must manually
                // specify this flag because of the added overhead with regards to resolving
                // the target of a link.
                foreach (FtpListItem item in client.GetListing(null,
                    FtpListOption.ForceList | FtpListOption.Modify | FtpListOption.DerefLinks)) {

                    Console.WriteLine(item);

                    if (item.Type == FtpFileSystemObjectType.Link && item.LinkObject != null) {
                        Console.WriteLine(item.LinkObject);
                    }
                }
            }
        }
コード例 #3
0
ファイル: GetListing.cs プロジェクト: Kylia669/DiplomWork
        public static void GetListing() {
            using (FtpClient conn = new FtpClient()) {
                conn.Host = "localhost";
                conn.Credentials = new NetworkCredential("ftptest", "ftptest");
                
                foreach (FtpListItem item in conn.GetListing(conn.GetWorkingDirectory(),
                    FtpListOption.Modify | FtpListOption.Size)) {

                    switch (item.Type) {
                        case FtpFileSystemObjectType.Directory:
                            break;
                        case FtpFileSystemObjectType.File:
                            break;
                        case FtpFileSystemObjectType.Link:
                            // derefernece symbolic links
                            if (item.LinkTarget != null) {
                                // see the DereferenceLink() example
                                // for more details about resolving links.
                                item.LinkObject = conn.DereferenceLink(item);

                                if (item.LinkObject != null) {
                                    // switch (item.LinkObject.Type)...
                                }
                            }
                            break;
                    }
                }

                // same example except automatically dereference symbolic links.
                // see the DereferenceLink() example for more details about resolving links.
                foreach (FtpListItem item in conn.GetListing(conn.GetWorkingDirectory(),
                    FtpListOption.Modify | FtpListOption.Size | FtpListOption.DerefLinks)) {

                    switch (item.Type) {
                        case FtpFileSystemObjectType.Directory:
                            break;
                        case FtpFileSystemObjectType.File:
                            break;
                        case FtpFileSystemObjectType.Link:
                            if (item.LinkObject != null) {
                                // switch (item.LinkObject.Type)...
                            }
                            break;
                    }
                }
            }
        }
コード例 #4
0
 public void TestIssue3()
 {
     var ftpClient = new FtpClient("anonymous",
                                   string.Empty,
                                   "ftp://ftp.mozilla.org");
     var ftpListItems = ftpClient.GetListing("/");
     Assert.IsNotNull(ftpListItems);
     Assert.IsTrue(ftpListItems.Any());
 }
コード例 #5
0
        static void TestDispose()
        {
            using (FtpClient cl = new FtpClient()) {
                cl.Credentials = new NetworkCredential(m_user, m_pass);
                cl.Host        = m_host;
                cl.Connect();
                // FTP server set to timeout after 5 seconds.
                //Thread.Sleep(6000);

                foreach (FtpListItem item in cl.GetListing())
                {
                }
            }
        }
コード例 #6
0
ファイル: Ex.cs プロジェクト: mpvyard/Ark.Tools
        public static IEnumerable <FtpListItem> GetFileListingRecursiveParallel(this FtpClient client, string startPath, FtpListOption options)
        {
            Policy retrier = Policy
                             .Handle <Exception>()
                             .WaitAndRetry(new[]
            {
                TimeSpan.FromSeconds(1),
                TimeSpan.FromSeconds(5),
                TimeSpan.FromSeconds(15)
            });

            if (options.HasFlag(FtpListOption.Recursive))
            {
                throw new ArgumentException("Do not use recursive option when doing a recursive listing.", "options");
            }

            List <Task <FtpListItem[]> > pending = new List <Task <FtpListItem[]> >();
            IEnumerable <FtpListItem>    files   = new List <FtpListItem>();

            Func <string, Task <FtpListItem[]> > listFolderAsync = (string path) =>
            {
                return(Task.Factory.StartNew(() =>
                {
                    return retrier.Execute(() =>
                    {
                        return client.GetListing(path, options);
                    });
                }));
            };

            pending.Add(listFolderAsync(startPath));

            int completedTaskIndex;

            while ((completedTaskIndex = Task.WaitAny(pending.ToArray())) != -1 && pending.Count > 0)
            {
                var t = pending.ElementAt(completedTaskIndex);
                pending.RemoveAt(completedTaskIndex);
                var list = t.Result;

                foreach (var d in list.Where(x => x.Type == FtpFileSystemObjectType.Directory))
                {
                    pending.Add(listFolderAsync(d.FullName));
                }

                files = files.Concat(list.Where(x => x.Type != FtpFileSystemObjectType.Directory).ToList());
            }

            return(files);
        }
コード例 #7
0
        public JArray GetIterativeFilesJson(FtpClient client, string path)
        {
            var files       = new JArray();
            var folderQueue = new Queue <FtpListItem>();

            try
            {
                // Adding root folder into queue
                folderQueue.Enqueue(new FtpListItem());

                while (folderQueue.Count != 0)
                {
                    var currentDirectory   = folderQueue.Dequeue();
                    var currentFolderFiles = new JArray();

                    var folder = new JObject(
                        new JProperty("name", currentDirectory.Name == null ? "/" : currentDirectory.Name),
                        new JProperty("modified", currentDirectory.Modified == DateTime.MinValue ? client.GetModifiedTime(path) : currentDirectory.Modified),
                        new JProperty("files", String.Empty));

                    files.Add(folder);

                    foreach (FtpListItem item in client.GetListing(currentDirectory.FullName))
                    {
                        if (item.Type == FtpFileSystemObjectType.File)
                        {
                            var obj = new JObject(
                                new JProperty("name", item.Name),
                                new JProperty("size", item.Size),
                                new JProperty("modified", item.Modified));

                            currentFolderFiles.Add(obj);
                        }
                        else
                        {
                            folderQueue.Enqueue(item);
                        }
                    }

                    files.Last["files"] = currentFolderFiles;
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
            }

            return(files);
        }
コード例 #8
0
ファイル: Tests.cs プロジェクト: worstenbrood/FluentFTP
        static void GetMicrosoftFTPListing()
        {
            using (FtpClient cl = new FtpClient()) {
                cl.Credentials = new NetworkCredential("ftp", "ftp");
                cl.Host        = "ftp.microsoft.com";
                cl.Connect();

                Console.WriteLine(cl.Capabilities);

                foreach (FtpListItem item in cl.GetListing(null, FtpListOption.Modify))
                {
                    Console.WriteLine(item.Modified);
                }
            }
        }
コード例 #9
0
        protected override IEnumerable <ContentSourceItem> ReadExistItems()
        {
            List <ContentSourceItem> items = new List <ContentSourceItem>();

            foreach (FtpListItem ftpListItem in _ftpClient.GetListing())
            {
                if (ftpListItem.Type != FtpFileSystemObjectType.File)
                {
                    continue;
                }
                Uri fileUri = new UriBuilder(Uri.UriSchemeFtp, _ftpClient.Host, _ftpClient.Port, ftpListItem.FullName).Uri;
                items.Add(new ContentSourceItem(ftpListItem.Created, fileUri));
            }
            return(items);
        }
コード例 #10
0
        internal bool CheckChmodFileOnServer(FtpClient ftpClient, String remoteDirectory, DFtpFile remoteSelection, int permissions)
        {
            //GetChmod is bugged
            FtpListItem[] list      = ftpClient.GetListing(remoteDirectory + "/" + remoteSelection.GetName());
            int           filePerms = list[0].Chmod;

            if (filePerms == permissions)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
コード例 #11
0
        /// <summary>
        /// Gets the directory content.
        /// </summary>
        /// <param name="serverConfiguration">The ftp server configuration.</param>
        /// <param name="directory">The directory</param>
        /// <returns></returns>
        public IList <string> GetDirectoryContent(FtpServerConfiguration serverConfiguration, string directory)
        {
            if (serverConfiguration == null)
            {
                throw new ArgumentNullException(nameof(serverConfiguration));
            }

            using (var client = new FtpClient(serverConfiguration.URI, serverConfiguration.Username, serverConfiguration.Password))
            {
                client.Connect();

                client.SetWorkingDirectory(directory ?? "");
                return(client.GetListing().Select(x => x.FullName).ToList());
            }
        }
コード例 #12
0
 public void DeleteDirectory(FtpClient cl, string path)
 {
     foreach (FtpListItem item in cl.GetListing(path))
     {
         if (item.Type == FtpFileSystemObjectType.File)
         {
             cl.DeleteFile(item.FullName);
         }
         else if (item.Type == FtpFileSystemObjectType.Directory)
         {
             DeleteDirectory(cl, item.FullName);
             cl.DeleteDirectory(item.FullName);
         }
     }
 }
コード例 #13
0
 public static void getfiles(List <string> resultlist, List <string> directorylist, string folder, FtpClient ftpclient)
 {
     foreach (FtpListItem item in ftpclient.GetListing(folder))
     {
         // if this is a file
         if (item.Type == FtpFileSystemObjectType.File)
         {
             resultlist.Add(item.FullName);
         }
         if (item.Type == FtpFileSystemObjectType.Directory)
         {
             directorylist.Add(item.FullName);
             getfiles(resultlist, directorylist, item.FullName, ftpclient);
         }
     }
 }
コード例 #14
0
ファイル: FTPAccess.cs プロジェクト: xmxth001/FtpSyncCore
        public List <string> GetFileList(string prefix)
        {
            List <string> files = new List <string>();

            foreach (FtpListItem item in _client.GetListing())
            {
                // if this is a file
                if (item.Type == FtpFileSystemObjectType.File)
                {
                    files.Add(item.Name);
                }
            }

            CleanFilesList(files, prefix);
            return(files);
        }
コード例 #15
0
        public void TestNetBSDServer()
        {
            using (FtpClient client = NewFtpClient_NetBsd())
            {
                foreach (FtpListItem item in client.GetListing(null,
                                                               FtpListOption.ForceList | FtpListOption.Modify | FtpListOption.DerefLinks))
                {
                    FtpTrace.WriteLine(item);

                    if (item.Type == FtpFileSystemObjectType.Link && item.LinkObject != null)
                    {
                        FtpTrace.WriteLine(item.LinkObject);
                    }
                }
            }
        }
コード例 #16
0
        static void TestServer()
        {
            using (FtpClient cl = new FtpClient()) {
                cl.Host                 = m_host;
                cl.Credentials          = new NetworkCredential(m_user, m_pass);
                cl.EncryptionMode       = FtpEncryptionMode.Explicit;
                cl.ValidateCertificate += (control, e) => {
                    e.Accept = true;
                };

                foreach (FtpListItem i in cl.GetListing("/"))
                {
                    FtpTrace.WriteLine(i.FullName);
                }
            }
        }
コード例 #17
0
        public static FileInf[] ListFiles(FtpClient client, int taskId)
        {
            var files = new List <FileInf>();

            var ftpListItems = client.GetListing();

            foreach (FtpListItem item in ftpListItems)
            {
                if (item.Type == FtpFileSystemObjectType.File)
                {
                    files.Add(new FileInf(item.FullName, taskId));
                }
            }

            return(files.ToArray());
        }
コード例 #18
0
ファイル: Tests.cs プロジェクト: worstenbrood/FluentFTP
        static void TestListSpacedPath()
        {
            using (FtpClient cl = new FtpClient()) {
                cl.Host                 = m_host;
                cl.Credentials          = new NetworkCredential(m_user, m_pass);
                cl.EncryptionMode       = FtpEncryptionMode.Explicit;
                cl.ValidateCertificate += (control, e) => {
                    e.Accept = true;
                };

                foreach (FtpListItem i in cl.GetListing("/public_html/temp/spaced folder/"))
                {
                    Console.WriteLine(i.FullName);
                }
            }
        }
コード例 #19
0
        public void Read_Directory(FtpListItem temp, string SourceFolder, string DestFolder)
        {
            dest_client.CreateDirectory(temp.FullName.Replace(SourceFolder, DestFolder));
            foreach (FtpListItem item in source_client.GetListing(temp.FullName))
            {
                if (item.Type == FtpFileSystemObjectType.File)
                {
                    Read_File(item, SourceFolder, DestFolder);
                }

                if (item.Type == FtpFileSystemObjectType.Directory)
                {
                    Read_Directory(item, SourceFolder, DestFolder);
                }
            }
        }
コード例 #20
0
ファイル: FtpController.cs プロジェクト: radtek/iPemSystem
        private List <FileModel> GetFtpFiles(string key, string name, bool cache)
        {
            var cachedKey = string.Format(GlobalCacheKeys.Ftp_Files_List, key);

            if (_cacheManager.IsSet(key) && !cache)
            {
                _cacheManager.Remove(key);
            }
            if (_cacheManager.IsSet(key))
            {
                return(_cacheManager.GetItemsFromList <FileModel>(key).ToList());
            }

            var files = new List <FileModel>();

            using (FtpClient conn = this.GetFtpClient(key)) {
                var index = 0;
                foreach (var item in conn.GetListing(conn.GetWorkingDirectory(), FtpListOption.Modify | FtpListOption.Size))
                {
                    if (item.Type == FtpFileSystemObjectType.File)
                    {
                        var created  = CommonHelper.DateTimeConverter(item.Created);
                        var modified = CommonHelper.DateTimeConverter(item.Modified);
                        var file     = new FileModel {
                            index = ++index,
                            name  = item.Name,
                            size  = string.Format("{0:N0} KB", item.Size / 1024),
                            type  = CommonHelper.GetFileType(item.Name),
                            date  = "--"
                        };

                        if (!string.IsNullOrWhiteSpace(created))
                        {
                            file.date = created;
                        }
                        else if (!string.IsNullOrWhiteSpace(modified))
                        {
                            file.date = modified;
                        }

                        files.Add(file);
                    }
                }
            }

            return(files);
        }
コード例 #21
0
        private void btnDistribute_Click(object sender, EventArgs e)        //Event handler for when the ditribute button is clicked
        {
            string filePathGet = listBox.GetItemText(listBox.SelectedItem); //Assigns the currently selected directory to a string variable

            if (filePathGet != null)                                        //Checks that the filepath is not empty
            {
                FtpClient clientFTP = new FtpClient();
                clientFTP.Host = "ftp://82.10.84.171";
                clientFTP.Port = 54443;
                clientFTP.Credentials.UserName         = "******";
                clientFTP.Credentials.Password         = "******";
                clientFTP.DataConnectionReadTimeout    = 2147483645;
                clientFTP.ConnectTimeout               = 2147483645;
                clientFTP.DataConnectionConnectTimeout = 2147483645;
                clientFTP.ReadTimeout = 2147483645;
                if (clientFTP.FileExists($@"/{filePathGet}")) //Checsk the file exists in the file directory of the FTP server
                {
                    string csvPath = Path.GetTempPath() + "tempcsv.csv";
                    clientFTP.DownloadFile(csvPath, filePathGet);                                                                                           //Downloads the file at the direcotry to the temporary CSV file
                    using (GetDistributionPath distriPath = new GetDistributionPath())                                                                      //Using the scope of a dialog box
                    {
                        if (distriPath.ShowDialog() == DialogResult.OK)                                                                                     //Given the user selects submit
                        {
                            if (distriPath.className != null)                                                                                               //And has selected a class name
                            {
                                listData = Global.CSVToArray(csvPath);                                                                                      //Passes the downlaoded CSV to a list of string arrays
                                listData[listData.Count - 1][3] = Global.currentUser;                                                                       //Adds the data of the teacher that distributed the quiz, and the class name distributed to
                                listData[listData.Count - 1][4] = distriPath.className;
                                Global.ArrayToCSV(listData);                                                                                                //Overwrites that temporary CSV file data with the edit
                                foreach (FtpListItem item in clientFTP.GetListing("/Classes/" + Global.currentUser + "/" + distriPath.className))           //Runs through each existing student in the distribution target class
                                {
                                    clientFTP.UploadFile(csvPath, $@"/Students/{item.Name.Substring(0, item.Name.Length - 4)}/{filePathGet.Substring(8)}"); //Uploads the CSV to every student account under the quiz title
                                }

                                MessageBox.Show("Quiz Distributed Successfully!"); //Informs user that the distribution was successful
                            }
                        }
                    }
                    File.Delete(csvPath); //Deletes the temporary CSV file
                    clientFTP.Disconnect();
                }
                else //Otherwise
                {
                    MessageBox.Show("File Not Found!"); //Informs the user that the file was not found
                }
            }
        }
コード例 #22
0
ファイル: Form1.cs プロジェクト: sbiliaiev/LeraFTPLoader
        private void Form1_Load(object sender, EventArgs e)
        {
            StreamReader   file;
            JsonTextReader reader;
            JObject        o2;

            try
            {
                Console.WriteLine("PATH " + Path.Combine(Environment.CurrentDirectory, "settings.json"));
                file   = File.OpenText(Path.Combine(Directory.GetCurrentDirectory(), "settings.json"));
                reader = new JsonTextReader(file);
                o2     = (JObject)JToken.ReadFrom(reader);


                Console.WriteLine("JSON " + o2.ToString());
                Console.WriteLine("LOGIN " + o2["login"]);
                Console.WriteLine("LOGIN " + o2["port"]);


                /*client = new FtpClient("127.0.0.1");
                 * client.Port = 54218;
                 * client.Credentials = new NetworkCredential("dev_user", "dev_user_pass");*/
                client = new FtpClient((string)o2["server"]);
                var tmp = (int)o2["port"];
                Console.WriteLine("TYPE " + tmp.GetType());
                client.Port        = tmp;
                client.Credentials = new NetworkCredential((string)o2["login"], (string)o2["password"]);
                NetworkCredential test1 = new NetworkCredential("test1_user", "test1_pass");
                NetworkCredential test2 = new NetworkCredential((string)o2["login"], (string)o2["password"]);
                client.Connect();

                List <string> cityList = new List <string>();

                foreach (FtpListItem item in client.GetListing("/"))
                {
                    cityList.Add(item.Name);
                }

                checkedListBox1.DataSource = cityList;
            }
            catch (Exception error)
            {
                Console.WriteLine("ERROR" + error.ToString());
                MessageBox.Show("Please, Create settings.json file");
                this.Close();
            }
        }
コード例 #23
0
        //[Fact]
        public void TestFilePermissions()
        {
            using (FtpClient cl = NewFtpClient())
            {
                foreach (FtpListItem i in cl.GetListing("/public_html/temp/"))
                {
                    FtpTrace.WriteLine(i.Name + " - " + i.Chmod);
                }

                FtpListItem o  = cl.GetFilePermissions("/public_html/temp/file3.exe");
                FtpListItem o2 = cl.GetFilePermissions("/public_html/temp/README.md");

                cl.SetFilePermissions("/public_html/temp/file3.exe", 646);

                int o22 = cl.GetChmod("/public_html/temp/file3.exe");
            }
        }
コード例 #24
0
        //[Fact]
        public void TestUnixListing()
        {
            using (FtpClient cl = NewFtpClient())
            {
                if (!cl.FileExists("test.txt"))
                {
                    using (Stream s = cl.OpenWrite("test.txt"))
                    {
                    }
                }

                foreach (FtpListItem i in cl.GetListing(null, FtpListOption.ForceList))
                {
                    FtpTrace.WriteLine(i);
                }
            }
        }
コード例 #25
0
ファイル: FtpHelper.cs プロジェクト: wc123hange/zfjl_media
        /// <summary>
        /// 取得文件或目录列表
        /// </summary>
        /// <param name="remoteDic">远程目录</param>
        /// <param name="type">类型:file-文件,dic-目录</param>
        /// <returns></returns>
        public List <string> ListDirectory(string remoteDic, string type = "file")
        {
            List <string> list = new List <string>();

            type = type.ToLower();

            try
            {
                if (Connect())
                {
                    FtpListItem[] files = ftpClient.GetListing(remoteDic);
                    foreach (FtpListItem file in files)
                    {
                        if (type == "file")
                        {
                            if (file.Type == FtpFileSystemObjectType.File)
                            {
                                list.Add(file.Name);
                            }
                        }
                        else if (type == "dic")
                        {
                            if (file.Type == FtpFileSystemObjectType.Directory)
                            {
                                list.Add(file.Name);
                            }
                        }
                        else
                        {
                            list.Add(file.Name);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                NLog.LogManager.GetCurrentClassLogger().Error("ListDirectory->取得文件或目录列表 异常:" + ex.ToString());
            }
            finally
            {
                DisConnect();
            }

            return(list);
        }
コード例 #26
0
        private int DownloadDirectory(string baseSrc, string dir, string des, FtpClient client)
        {
            string target = FormatDirectoryName(des + dir);

            if (Directory.Exists(target))
            {
                Directory.Delete(target, true);
            }

            Directory.CreateDirectory(target);
            var           list   = client.GetListing(FormatDirectoryName(baseSrc + dir));
            List <string> dirs   = new List <string>();
            int           result = 0;

            foreach (var i in list)
            {
                switch (i.Type)
                {
                case FtpFileSystemObjectType.File:
                    if (client.DownloadFile(target + i.Name, i.FullName))
                    {
                        ++result;
                    }

                    break;

                case FtpFileSystemObjectType.Directory:
                    dirs.Add(i.Name);
                    break;

                case FtpFileSystemObjectType.Link:
                    break;

                default:
                    break;
                }
            }

            foreach (var i in dirs)
            {
                result += DownloadDirectory(baseSrc, dir + i + "/", des, client);
            }

            return(result);
        }
コード例 #27
0
        public void ListMinorDirectory() //Subroutine to list the directory of the selected item in the first list box
        {
            listBox2.Items.Clear();
            FtpClient clientFTP = new FtpClient();

            clientFTP.Host = "ftp://82.10.84.171";
            clientFTP.Port = 54443;
            clientFTP.Credentials.UserName         = "******";
            clientFTP.Credentials.Password         = "******";
            clientFTP.DataConnectionReadTimeout    = 2147483645;
            clientFTP.ConnectTimeout               = 2147483645;
            clientFTP.DataConnectionConnectTimeout = 2147483645;
            clientFTP.ReadTimeout = 2147483645;
            foreach (FtpListItem item in clientFTP.GetListing(listBox1.GetItemText(listBox1.SelectedItem))) //Runs through each file in the directory selected, adding the file names to the second list box
            {
                listBox2.Items.Add(item.Name);
            }
        }
コード例 #28
0
        public void ListDirectory() //Subroutine to refresh the list box to the directory of the
        {
            listBox.Items.Clear();  //Clears the list boxes current items
            FtpClient clientFTP = new FtpClient();

            clientFTP.Host = "ftp://82.10.84.171";
            clientFTP.Port = 54443;
            clientFTP.Credentials.UserName         = "******";
            clientFTP.Credentials.Password         = "******";
            clientFTP.DataConnectionReadTimeout    = 2147483645;
            clientFTP.ConnectTimeout               = 2147483645;
            clientFTP.DataConnectionConnectTimeout = 2147483645;
            clientFTP.ReadTimeout = 2147483645;
            foreach (FtpListItem item in clientFTP.GetListing("Quizzes/")) //Runs through all the directory listings in the Quizzes directory of the FTP server
            {
                listBox.Items.Add(item.FullName);                          //Adds each directory to the list box
            }
        }
コード例 #29
0
        public void ListDirectory()         //Subroutine to list the directory of the currently logged in user
        {
            listBox1.Items.Clear();
            FtpClient clientFTP = new FtpClient();

            clientFTP.Host = "ftp://82.10.84.171";
            clientFTP.Port = 54443;
            clientFTP.Credentials.UserName         = "******";
            clientFTP.Credentials.Password         = "******";
            clientFTP.DataConnectionReadTimeout    = 2147483645;
            clientFTP.ConnectTimeout               = 2147483645;
            clientFTP.DataConnectionConnectTimeout = 2147483645;
            clientFTP.ReadTimeout = 2147483645;
            foreach (FtpListItem item in clientFTP.GetListing($@"Classes/{Global.currentUser}")) //Runs through each directory, adding them to the list box
            {
                listBox1.Items.Add(item.FullName);
            }
        }
コード例 #30
0
ファイル: Tests.cs プロジェクト: worstenbrood/FluentFTP
        static void TestNetBSDServer()
        {
            using (FtpClient client = new FtpClient()) {
                client.Credentials = new NetworkCredential("ftp", "ftp");
                client.Host        = "ftp.netbsd.org";

                foreach (FtpListItem item in client.GetListing(null,
                                                               FtpListOption.ForceList | FtpListOption.Modify | FtpListOption.DerefLinks))
                {
                    Console.WriteLine(item);

                    if (item.Type == FtpFileSystemObjectType.Link && item.LinkObject != null)
                    {
                        Console.WriteLine(item.LinkObject);
                    }
                }
            }
        }
コード例 #31
0
ファイル: Loader.cs プロジェクト: AlienJust/RPD
 /// <summary>
 /// Получает список репозиториев FTP сервера
 /// </summary>
 /// <param name="ftpHost">Адрес узла (IP-адрес или доменное имя)</param>
 /// <param name="ftpPort">TCP порт, на котором расположен FTP сервер</param>
 /// <param name="ftpUsername">Имя пользователя FTP сервера</param>
 /// <param name="ftpPassword">Пароль пользователя FTP сервера</param>
 /// <param name="callbackAction">Действие обратного вызова по получению списка репозиториев</param>
 public void GetFtpRepositoryInfosAsync(string ftpHost, int ftpPort, string ftpUsername, string ftpPassword, Action <OnCompleteEventArgs, IEnumerable <IFtpRepositoryInfo> > callbackAction)
 {
     _backWorker.AddWork(
         () => {
         try {
             var result = new List <IFtpRepositoryInfo>();
             using (var conn = new FtpClient()) {
                 conn.Host        = ftpHost;
                 conn.Port        = ftpPort;
                 conn.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
                 var items        = conn.GetListing();                          // list root items
                 foreach (var ftpListItem in items)
                 {
                     try {
                         if (ftpListItem.Type == FtpFileSystemObjectType.Directory)
                         {
                             var deviceNumber = int.Parse(ftpListItem.Name);
                             result.Add(new FtpRepositoryInfoSimple {
                                 DeviceNumber = deviceNumber,
                                 FtpHost      = ftpHost,
                                 FtpPassword  = ftpPassword,
                                 FtpPort      = ftpPort,
                                 FtpUsername  = ftpUsername
                             });
                         }
                     }
                     catch /*(Exception ex)*/ {
                         continue;                                         // FTP server can contain some other directories
                     }
                 }
             }
             if (callbackAction != null)
             {
                 _uiNotifier.Notify(() => callbackAction(new OnCompleteEventArgs(OnCompleteEventArgs.CompleteResult.Error, "Список устройств получен"), result));
             }
         }
         catch (Exception ex) {
             if (callbackAction != null)
             {
                 _uiNotifier.Notify(() => callbackAction(new OnCompleteEventArgs(OnCompleteEventArgs.CompleteResult.Error, ex.ToString()), null));
             }
         }
     });
 }
コード例 #32
0
ファイル: Tests.cs プロジェクト: worstenbrood/FluentFTP
        static void TestFilePermissions()
        {
            using (FtpClient cl = new FtpClient()) {
                cl.Host        = m_host;
                cl.Credentials = new NetworkCredential(m_user, m_pass);

                foreach (FtpListItem i in cl.GetListing("/public_html/temp/"))
                {
                    Console.WriteLine(i.Name + " - " + i.Chmod);
                }

                FtpListItem o  = cl.GetFilePermissions("/public_html/temp/file3.exe");
                FtpListItem o2 = cl.GetFilePermissions("/public_html/temp/README.md");

                cl.SetFilePermissions("/public_html/temp/file3.exe", 646);

                int o22 = cl.GetChmod("/public_html/temp/file3.exe");
            }
        }
コード例 #33
0
        public List <string> Select()
        {
            try
            {
                List <string> items;
                using (FtpClient ftpClient = new FtpClient(Host, Port, Username, Password))
                {
                    if (!string.IsNullOrWhiteSpace(RemoteWorkingDir))
                    {
                        ftpClient.SetWorkingDirectory(RemoteWorkingDir);
                    }

                    var listing = ftpClient.GetListing(SearchPattern).ToList();
                    // Logger.Debug($"First Listing: {listing.Count}");
                    List <FtpFileSystemObjectType> targetTypes = new List <FtpFileSystemObjectType>();

                    if (SelectFiles)
                    {
                        targetTypes.Add(FtpFileSystemObjectType.File);
                    }

                    if (SelectDirectories)
                    {
                        targetTypes.Add(FtpFileSystemObjectType.Directory);
                    }

                    listing = listing.Where(item => targetTypes.Contains(item.Type)).ToList();
                    //Logger.Debug($"Limited by type: {listing.Count}");
                    listing = GetFilesFilteredByTime(listing);
                    // Logger.Debug($"Filtered per time: {listing.Count}");
                    items = GetSortedFiles(listing)
                            .Take(MaximumFiles)
                            .Select(e => e.FullName).ToList();
                }

                return(items);
            }
            catch (Exception exception)
            {
                Logger.Error(exception);
                return(new List <string>());
            }
        }
コード例 #34
0
ファイル: Tests.cs プロジェクト: worstenbrood/FluentFTP
        static void TestUnixListing()
        {
            using (FtpClient cl = new FtpClient()) {
                cl.Host        = m_host;
                cl.Credentials = new NetworkCredential(m_user, m_pass);

                if (!cl.FileExists("test.txt"))
                {
                    using (Stream s = cl.OpenWrite("test.txt")) {
                        s.Close();
                    }
                }

                foreach (FtpListItem i in cl.GetListing(null, FtpListOption.ForceList))
                {
                    Console.WriteLine(i);
                }
            }
        }
コード例 #35
0
        public void TestWorkFlow()
        {
            var config = SetupBootstrap("Basic.config");

            using(var client = new FtpClient())
            {
                client.Host = "localhost";
                client.InternetProtocolVersions = FtpIpVersion.IPv4;
                client.Credentials = new NetworkCredential("kerry", "123456");
                client.DataConnectionType = FtpDataConnectionType.PASV;
                client.Connect();
                Assert.AreEqual(true, client.IsConnected);
                var workDir = client.GetWorkingDirectory();
                Assert.AreEqual("/", workDir);
                Console.WriteLine("EncryptionMode: {0}", client.EncryptionMode);
                foreach (var item in client.GetListing(workDir, FtpListOption.Size))
                {
                    Console.WriteLine(item.Name);
                }
            }
        }
コード例 #36
0
ファイル: MainWnd.cs プロジェクト: marioricci/erp-luma
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            // Get the BackgroundWorker that raised this event.
            BackgroundWorker worker = sender as BackgroundWorker;

            try
            {
                string strServer = "127.0.0.1";
                if (System.Configuration.ConfigurationManager.AppSettings["VersionFTPIPAddress"] != null)
                {
                    try { strServer = System.Configuration.ConfigurationManager.AppSettings["VersionFTPIPAddress"].ToString(); }
                    catch { }
                }

                int intPort = 21;
                if (System.Configuration.ConfigurationManager.AppSettings["VersionFTPPort"] != null)
                {
                    try { intPort = int.Parse(System.Configuration.ConfigurationManager.AppSettings["VersionFTPPort"]); }
                    catch { }
                }

                string strUserName = "******";
                string strPassword = "******";
                string strFTPDirectory = "retailplusclient";

                string destinationDirectory = Application.StartupPath;
                //string strConstantRemarks = "Please contact your system administrator immediately.";

                mstStatus = "getting ftp server configuration...";
                worker.ReportProgress(1);

                FtpClient ftpClient = new FtpClient();
                ftpClient.Host = strServer;
                ftpClient.Port = intPort;
                ftpClient.Credentials = new NetworkCredential(strUserName, strPassword);

                mstStatus = "connecting to ftp server " + strServer + "...";
                worker.ReportProgress(2);

                //IEnumerable<FtpListItem> lstFtpListItem = ftpClient.GetListing(strFTPDirectory, FtpListOption.Modify | FtpListOption.Size)
                //        .Where(ftpListItem => string.Equals(Path.GetExtension(ftpListItem.Name), ".dll"));

                IEnumerable<FtpListItem> lstFtpListItem = ftpClient.GetListing(strFTPDirectory, FtpListOption.Modify | FtpListOption.Size);

                mstStatus = "connecting to ftp server " + strServer + "... done.";
                worker.ReportProgress(5);
                System.Threading.Thread.Sleep(10);

                Int32 iCount =  lstFtpListItem.Count();
                Int32 iCtr = 1;

                mstStatus = "copying " + iCount.ToString() + " files from retailplusclient...";
                worker.ReportProgress(10);
                System.Threading.Thread.Sleep(10);

                // List all files with a .txt extension
                foreach (FtpListItem ftpListItem in lstFtpListItem)
                {
                    if (ftpListItem.Name.ToLower() != "version.xml" &&
                        ftpListItem.Name.ToLower() != "retailplus.versionchecker.exe" &
                        ftpListItem.Name.ToLower() != "retailplus.versionchecker.exe.config")
                    {
                        // Report progress as a percentage of the total task. 
                        mstStatus = "copying file: " + ftpListItem.Name + " ...";
                        decimal x = ((decimal.Parse(iCtr.ToString()) / decimal.Parse(iCount.ToString()) * decimal.Parse("100")) - decimal.Parse("1"));
                        iCtr++;

                        Int32 iProgress = Int32.Parse(Math.Round(x, 0).ToString());
                        worker.ReportProgress(iProgress >= 90 ? 90 : iProgress);

                        var destinationPath = string.Format(@"{0}\{1}", destinationDirectory, ftpListItem.Name);

                        using (var ftpStream = ftpClient.OpenRead(ftpListItem.FullName))
                        using (var fileStream = File.Create(destinationPath, (int)ftpStream.Length))
                        {
                            var buffer = new byte[8 * 1024];
                            int count;
                            while ((count = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                fileStream.Write(buffer, 0, count);
                            }
                        }
                    }
                }

                mstStatus = "Done copying all files...";

                worker.ReportProgress(100);
                System.Threading.Thread.Sleep(100);
                System.Diagnostics.Process.Start(ExecutableSender);
                Application.Exit();
            }
            catch { }
        }
コード例 #37
0
ファイル: FtpServer.cs プロジェクト: haizhixing126/PYSConsole
        public List<FtpFile> GetListFiles()
        {
            List<FtpFile> listFtpFiles = new List<FtpFile>();

            StringBuilder requestUri = new StringBuilder();
            if (string.IsNullOrEmpty(this.Path))
            {
                requestUri.Append("/");
            }
            else
            {
                if (!this.Password.StartsWith("/"))
                {
                    requestUri.Append("/");
                }
                requestUri.Append(Path);
                if (!Path.EndsWith("/"))
                {
                    requestUri.Append("'/");
                }
            }

            FtpClient ftpClient = new FtpClient(UserName, Password, HostName);

            FtpListItem[] listItems = ftpClient.GetListing(requestUri.ToString());
            foreach (FtpListItem item in listItems)
            {
                FtpFile ftpFile = new FtpFile()
                {
                    FileType = item.Type.ToString(),
                    Name = item.Name,
                    LastWriteTime = item.Modify
                };
                listFtpFiles.Add(ftpFile);
            }
            return listFtpFiles;
        }
コード例 #38
0
ファイル: Program.cs プロジェクト: marioricci/erp-luma
        private static Version GetLatestVersion()
        {
            Version clsVersion = new Version("0.0.0.0");
            try
            {
                string strServer = "127.0.0.1";
                if (System.Configuration.ConfigurationManager.AppSettings["VersionFTPIPAddress"] != null)
                {
                    try { strServer = System.Configuration.ConfigurationManager.AppSettings["VersionFTPIPAddress"].ToString(); }
                    catch { }
                }

                int intPort = 21;
                if (System.Configuration.ConfigurationManager.AppSettings["VersionFTPPort"] != null)
                {
                    try { intPort = int.Parse(System.Configuration.ConfigurationManager.AppSettings["VersionFTPPort"]); }
                    catch { }
                }

                string strUserName = "******";
                if (System.Configuration.ConfigurationManager.AppSettings["VersionFTPUserName"] != null)
                {
                    try { strUserName = System.Configuration.ConfigurationManager.AppSettings["VersionFTPUserName"].ToString(); }
                    catch { }
                }

                string strPassword = "******";
                if (System.Configuration.ConfigurationManager.AppSettings["VersionFTPPassword"] != null)
                {
                    try { strPassword = System.Configuration.ConfigurationManager.AppSettings["VersionFTPPassword"].ToString(); }
                    catch { }
                }

                string strFTPDirectory = "RetailPlusClient";
                if (System.Configuration.ConfigurationManager.AppSettings["VersionFTPDirectory"] != null)
                {
                    try { strFTPDirectory = System.Configuration.ConfigurationManager.AppSettings["VersionFTPDirectory"].ToString(); }
                    catch { }
                }

                string strXMLFile = Application.StartupPath + "\\version.xml";
                string destinationDirectory = Application.StartupPath;

                FtpClient ftpClient = new FtpClient();
                ftpClient.Host = strServer;
                ftpClient.Port = intPort;
                ftpClient.Credentials = new NetworkCredential(strUserName, strPassword);

                System.Collections.Generic.IEnumerable<FtpListItem> lstFtpListItem = ftpClient.GetListing(strFTPDirectory, FtpListOption.Modify | FtpListOption.Size);

                // List all files with a .txt extension
                foreach (FtpListItem ftpListItem in lstFtpListItem)
                {
                    if (ftpListItem.Name.ToLower() == "version.xml" ||
                        ftpListItem.Name.ToLower() == "retailplus.versionchecker.exe" ||
                        ftpListItem.Name.ToLower() == "retailplus.versionchecker.exe.config")
                    {

                        var destinationPath = string.Format(@"{0}\{1}", destinationDirectory, ftpListItem.Name);

                        using (var ftpStream = ftpClient.OpenRead(ftpListItem.FullName))
                        using (var fileStream = File.Create(destinationPath, (int)ftpStream.Length))
                        {
                            var buffer = new byte[8 * 1024];
                            int count;
                            while ((count = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                fileStream.Write(buffer, 0, count);
                            }
                        }
                    }
                }

                string strVersion = string.Empty;
                #region Assign the Version from XML File to strVersion
                XmlReader xmlReader = new XmlTextReader(strXMLFile);
                xmlReader.MoveToContent();
                string strElementName = string.Empty;

                if ((xmlReader.NodeType == XmlNodeType.Element) && (xmlReader.Name == "RetailPlus"))
                {
                    while (xmlReader.Read())
                    {
                        // we remember its name  
                        if (xmlReader.NodeType == XmlNodeType.Element)
                            strElementName = xmlReader.Name;
                        else
                        {
                            // for text nodes...  
                            if ((xmlReader.NodeType == XmlNodeType.Text) && (xmlReader.HasValue))
                            {
                                // we check what the name of the node was  
                                switch (strElementName)
                                {
                                    case "version":
                                        strVersion = xmlReader.Value;
                                        break;
                                }
                            }
                        }
                        if (!string.IsNullOrEmpty(strVersion)) break;
                    }
                }
                if (xmlReader != null) xmlReader.Close();

                #endregion

                clsVersion = new Version(strVersion);
            }
            catch
            { }

            return clsVersion;
        }
コード例 #39
0
ファイル: Program.cs プロジェクト: marioricci/erp-luma
        private static bool getSubGroupImages()
        {
            try
            {
                string strServer = "127.0.0.1";
                if (System.Configuration.ConfigurationManager.AppSettings["VersionFTPIPAddress"] != null)
                {
                    try { strServer = System.Configuration.ConfigurationManager.AppSettings["VersionFTPIPAddress"].ToString(); }
                    catch { }
                }

                int intPort = 21;
                if (System.Configuration.ConfigurationManager.AppSettings["VersionFTPPort"] != null)
                {
                    try { intPort = int.Parse(System.Configuration.ConfigurationManager.AppSettings["VersionFTPPort"]); }
                    catch { }
                }

                string strUserName = "******";
                string strPassword = "******";
                string strFTPDirectory = "subgroupimages";

                string destinationDirectory = Application.StartupPath + @"\images\subgroups";

                FtpClient ftpClient = new FtpClient();
                ftpClient.Host = strServer;
                ftpClient.Port = intPort;
                ftpClient.Credentials = new NetworkCredential(strUserName, strPassword);

                System.Collections.Generic.IEnumerable<FtpListItem> lstFtpListItem = ftpClient.GetListing(strFTPDirectory, FtpListOption.Modify | FtpListOption.Size);

                // List all files with a .txt extension
                foreach (FtpListItem ftpListItem in lstFtpListItem)
                {
                    var destinationPath = string.Format(@"{0}\{1}", destinationDirectory, ftpListItem.Name);

                    using (var ftpStream = ftpClient.OpenRead(ftpListItem.FullName))
                    using (var fileStream = File.Create(destinationPath, (int)ftpStream.Length))
                    {
                        var buffer = new byte[8 * 1024];
                        int count;
                        while ((count = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            fileStream.Write(buffer, 0, count);
                        }
                    }
                }
            }
            catch
            { }
            return true;
        }
コード例 #40
0
ファイル: Ayala.cs プロジェクト: marioricci/erp-luma
        private void TransferFile(string pvtFileName)
        {
            Event clsEvent = new Event();
            try
            {
                if (!string.IsNullOrEmpty(pvtFileName))
                {
                    if (string.IsNullOrEmpty(mclsAyalaDetails.FTPIPAddress))
                    { 
                        clsEvent.AddEventLn("Cannot transfer file " + pvtFileName + ". FTP IPAddress is empty Automatic File transfer is disabled.", true); 
                        return; 
                    }
                    else
                        clsEvent.AddEventLn("Transferring " + pvtFileName + " to " + mclsAyalaDetails.FTPIPAddress, true);
                }
                else
                {
                    clsEvent.AddEventLn("Cannot transfer an blank file.", true); return;
                }

                int intPort = 21;
                if (System.Configuration.ConfigurationManager.AppSettings["VersionFTPPort"] != null)
                {
                    try { intPort = int.Parse(System.Configuration.ConfigurationManager.AppSettings["VersionFTPPort"]); }
                    catch { }
                }

                FtpClient ftpClient = new FtpClient();
                ftpClient.Host = mclsAyalaDetails.FTPIPAddress;
                ftpClient.Port = intPort;
                ftpClient.Credentials = new NetworkCredential(mclsAyalaDetails.FTPUsername, mclsAyalaDetails.FTPPassword);

                IEnumerable<FtpListItem> lstFtpListItem = ftpClient.GetListing(mclsAyalaDetails.FTPDirectory, FtpListOption.Modify | FtpListOption.Size);

                bool bolIsFileExist = false;
                clsEvent.AddEventLn("Checking file if already exist...", true);
                try
                {
                    foreach (FtpListItem ftpListItem in lstFtpListItem)
                    {
                        if (ftpListItem.Name.ToUpper() == Path.GetFileName(pvtFileName).ToUpper())
                        { bolIsFileExist = true; break; }
                    }
                }
                catch (Exception excheck)
                {
                    clsEvent.AddEventLn("checking error..." + excheck.Message, true);
                }

                if (bolIsFileExist)
                {
                    clsEvent.AddEventLn("exist...", true);
                    clsEvent.AddEventLn("uploading now...", true);
                }
                else
                {
                    clsEvent.AddEventLn("does not exist...", true);
                    clsEvent.AddEventLn("uploading now...", true);
                }

                using (var fileStream = File.OpenRead(pvtFileName))
                using (var ftpStream = ftpClient.OpenWrite(string.Format("{0}/{1}", Path.GetFileName(pvtFileName), Path.GetFileName(pvtFileName))))
                {
                    var buffer = new byte[8 * 1024];
                    int count;
                    while ((count = fileStream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        ftpStream.Write(buffer, 0, count);
                    }
                    clsEvent.AddEventLn("Upload Complete: TotalBytes: " + buffer.ToString(), true);
                }

                ftpClient.Disconnect();
                ftpClient.Dispose();
                ftpClient = null;

                clsEvent.AddEventLn("Done.", true);
            }
            catch (Exception ex)
            {
                clsEvent.AddEventLn("Error encountered: " + ex.Message, true);
                throw new IOException("Sales file is not sent to RLC server. Please contact your POS vendor");
            }
        }
コード例 #41
0
        private void AttachFile()
        {
            try
            {
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.Multiselect = false;
                
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    string fileName = System.IO.Path.GetFileName(ofd.FileName);
                    string filePath = System.IO.Path.GetFullPath(ofd.FileName);

                    string strNewFileName = SalesTransactionItemDetails.TransactionID.ToString() + "_" + SalesTransactionItemDetails.TransactionItemsID + "_" + fileName;

                    Data.SalesTransactionItemAttachmentDetails clsDetails = new Data.SalesTransactionItemAttachmentDetails();
                    clsDetails.TransactionItemAttachmentsID = 0;
                    clsDetails.TransactionItemsID = SalesTransactionItemDetails.TransactionItemsID;
                    clsDetails.TransactionID = SalesTransactionItemDetails.TransactionID;
                    clsDetails.OrigFileName = fileName;
                    clsDetails.FileName = strNewFileName;
                    clsDetails.UploadedByName = CashierName;
                    clsDetails.CreatedOn = DateTime.Now;
                    clsDetails.LastModified = clsDetails.CreatedOn;

                    Data.SalesTransactionItemAttachments clsSalesTransactionItemAttachments = new Data.SalesTransactionItemAttachments();
                    clsSalesTransactionItemAttachments.Insert(clsDetails);
                    clsSalesTransactionItemAttachments.CommitAndDispose();

                    try
                    {
                        string strServer = "127.0.0.1";
                        if (System.Configuration.ConfigurationManager.AppSettings["VersionFTPIPAddress"] != null)
                        {
                            try { strServer = System.Configuration.ConfigurationManager.AppSettings["VersionFTPIPAddress"].ToString(); }
                            catch { }
                        }

                        int intPort = 21;
                        if (System.Configuration.ConfigurationManager.AppSettings["VersionFTPPort"] != null)
                        {
                            try { intPort = int.Parse(System.Configuration.ConfigurationManager.AppSettings["VersionFTPPort"]); }
                            catch { }
                        }

                        string strUserName = "******";
                        string strPassword = "******";
                        string strFTPDirectory = "attachment";

                        string destinationDirectory = Application.StartupPath;
                        //string strConstantRemarks = "Please contact your system administrator immediately.";

                        FtpClient ftpClient = new FtpClient();
                        ftpClient.Host = strServer;
                        ftpClient.Port = intPort;
                        ftpClient.Credentials = new NetworkCredential(strUserName, strPassword);

                        IEnumerable<FtpListItem> lstFtpListItem = ftpClient.GetListing(strFTPDirectory, FtpListOption.Modify | FtpListOption.Size);


                        Event clsEvent = new Event();

                        bool bolIsFileExist = false;
                        clsEvent.AddEventLn("Checking file if already exist...", true);
                        try
                        {
                            foreach (FtpListItem ftpListItem in lstFtpListItem)
                            {
                                if (ftpListItem.Name.ToUpper() == Path.GetFileName(strNewFileName).ToUpper())
                                { bolIsFileExist = true; break; }
                            }
                        }
                        catch (Exception excheck)
                        {
                            clsEvent.AddEventLn("checking error..." + excheck.Message, true);
                        }

                        if (bolIsFileExist)
                        {
                            clsEvent.AddEventLn("exist...", true);
                            clsEvent.AddEventLn("uploading now...", true);
                        }
                        else
                        {
                            clsEvent.AddEventLn("does not exist...", true);
                            clsEvent.AddEventLn("uploading now...", true);
                        }

                        using (var fileStream = File.OpenRead(filePath))
                        using (var ftpStream = ftpClient.OpenWrite(string.Format("{0}/{1}", strFTPDirectory, Path.GetFileName(strNewFileName))))
                        {
                            var buffer = new byte[8 * 1024];
                            int count;
                            while ((count = fileStream.Read(buffer, 0, buffer.Length)) > 0)
                            {
                                ftpStream.Write(buffer, 0, count);
                            }
                            clsEvent.AddEventLn("Upload Complete: TotalBytes: " + buffer.ToString(), true);
                        }

                        ftpClient.Disconnect();
                        ftpClient.Dispose();
                        ftpClient = null;
                    }
                    catch { }

                    LoadData();

                    MessageBox.Show("The attachment: " + fileName + " has been uploaded.", "RetailPlus", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "RetailPlus", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
コード例 #42
0
        private void OpenAttachment()
        {
            try
            {
                string strTempPath = Application.StartupPath + "/temp/";
                string strFile = "";

                if (dgvItems.SelectedRows.Count == 1)
                {
                    if (!Directory.Exists(strTempPath)) Directory.CreateDirectory(strTempPath);

                    foreach (DataGridViewRow dr in dgvItems.SelectedRows)
                    {
                        strFile = strTempPath + dr.Cells["FileName"].Value.ToString();

                        if (System.IO.File.Exists(strFile))
                        try { System.IO.File.Delete(strFile); }
                        catch { }

                        #region Download

                        try
                        {
                            string strServer = "127.0.0.1";
                            if (System.Configuration.ConfigurationManager.AppSettings["VersionFTPIPAddress"] != null)
                            {
                                try { strServer = System.Configuration.ConfigurationManager.AppSettings["VersionFTPIPAddress"].ToString(); }
                                catch { }
                            }

                            int intPort = 21;
                            if (System.Configuration.ConfigurationManager.AppSettings["VersionFTPPort"] != null)
                            {
                                try { intPort = int.Parse(System.Configuration.ConfigurationManager.AppSettings["VersionFTPPort"]); }
                                catch { }
                            }

                            string strUserName = "******";
                            string strPassword = "******";
                            string strFTPDirectory = "attachment";

                            FtpClient ftpClient = new FtpClient();
                            ftpClient.Host = strServer;
                            ftpClient.Port = intPort;
                            ftpClient.Credentials = new NetworkCredential(strUserName, strPassword);

                            //IEnumerable<FtpListItem> lstFtpListItem = ftpClient.GetListing(strFTPDirectory, FtpListOption.Modify | FtpListOption.Size)
                            //        .Where(ftpListItem => string.Equals(Path.GetExtension(ftpListItem.Name), ".dll"));

                            IEnumerable<FtpListItem> lstFtpListItem = ftpClient.GetListing(strFTPDirectory, FtpListOption.Modify | FtpListOption.Size);

                            Int32 iCount = lstFtpListItem.Count();
                            Int32 iCtr = 1;

                            // List all files with a .txt extension
                            foreach (FtpListItem ftpListItem in lstFtpListItem)
                            {
                                if (ftpListItem.Name.ToLower() == dr.Cells["FileName"].Value.ToString().ToLower())
                                {
                                    // Report progress as a percentage of the total task. 
                                    decimal x = ((decimal.Parse(iCtr.ToString()) / decimal.Parse(iCount.ToString()) * decimal.Parse("100")) - decimal.Parse("1"));
                                    iCtr++;

                                    strFile = string.Format(@"{0}{1}", strTempPath, ftpListItem.Name);

                                    using (var ftpStream = ftpClient.OpenRead(ftpListItem.FullName))
                                    using (var fileStream = File.Create(strFile, (int)ftpStream.Length))
                                    {
                                        var buffer = new byte[8 * 1024];
                                        int count;
                                        while ((count = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
                                        {
                                            fileStream.Write(buffer, 0, count);
                                        }
                                    }

                                    //System.Diagnostics.Process.Start(strFile);

                                    try
                                    { Common.OpenFileToDOS(strFile); }
                                    catch (Exception ex)
                                    {
                                        MessageBox.Show("Error opening file. You may directly open the file @: " + strFile + Environment.NewLine + "Error details: " + ex.InnerException.Message, "RetailPlus", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("Error opening file, the system cannot connect to FTP server. Please consult your System Administrator." + Environment.NewLine + "Error details: " + ex.InnerException.Message, "RetailPlus", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }

                        #endregion
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "RetailPlus", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
コード例 #43
0
ファイル: ForwarderWnd.cs プロジェクト: marioricci/erp-luma
        private void ShowRLCServerFileViewer()
        {
            ListViewItem lvi;
            ListViewItem.ListViewSubItem lvsi;
            lstItems.Items.Clear();

            int intPort = 21;
            if (System.Configuration.ConfigurationManager.AppSettings["VersionFTPPort"] != null)
            {
                try { intPort = int.Parse(System.Configuration.ConfigurationManager.AppSettings["VersionFTPPort"]); }
                catch { }
            }

            FtpClient ftpClient = new FtpClient();
            ftpClient.Host = CONFIG.FTPIPAddress;
            ftpClient.Port = intPort;
            ftpClient.Credentials = new NetworkCredential(CONFIG.FTPUsername, CONFIG.FTPPassword);

            IEnumerable<FtpListItem> lstFtpListItem = ftpClient.GetListing(CONFIG.FTPDirectory, FtpListOption.Modify | FtpListOption.Size);
            
            grpRLC.Text = "RLC File Server Management: [DOUBLE CLICK TO RELOAD] : " + CONFIG.FTPDirectory;

            //Int32 iCount = lstFtpListItem.Count();
            //Int32 iCtr = 1;
            try
            {
                foreach (FtpListItem ftpListItem in lstFtpListItem)
                {
                    lvi = new ListViewItem();
                    lvi.Text = ftpListItem.Name;
                    //lvi.ImageIndex = 0;
                    lvi.Tag = ftpListItem.FullName;

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

                    lvsi = new ListViewItem.ListViewSubItem();
                    lvsi.Text = ftpListItem.Created.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);
            }

            ftpClient.Disconnect();
            ftpClient.Dispose();
            ftpClient = null;
        }