예제 #1
0
        static void TestHash()
        {
            using (FtpClient cl = new FtpClient()) {
                cl.Credentials = new NetworkCredential(m_user, m_pass);
                cl.Host        = m_host;
                cl.Connect();

                Console.WriteLine("Supported HASH algorithms: {0}", cl.HashAlgorithms);
                Console.WriteLine("Current HASH algorithm: {0}", cl.GetHashAlgorithm());

                foreach (FtpHashAlgorithm alg in Enum.GetValues(typeof(FtpHashAlgorithm)))
                {
                    if (alg != FtpHashAlgorithm.NONE && cl.HashAlgorithms.HasFlag(alg))
                    {
                        FtpHash hash = null;

                        cl.SetHashAlgorithm(alg);
                        hash = cl.GetHash("LICENSE.TXT");

                        if (hash.IsValid)
                        {
                            Debug.Assert(hash.Verify(@"C:\FTPTEST\LICENSE.TXT"), "The computed hash didn't match or the hash object was invalid!");
                        }
                    }
                }
            }
        }
예제 #2
0
        //[Fact]
        public async Task TestHashAsync()
        {
            using (FtpClient cl = NewFtpClient())
            {
                await cl.ConnectAsync();

                FtpTrace.WriteLine("Supported HASH algorithms: " + cl.HashAlgorithms);
                FtpTrace.WriteLine("Current HASH algorithm: " + await cl.GetHashAlgorithmAsync());

                foreach (FtpHashAlgorithm alg in Enum.GetValues(typeof(FtpHashAlgorithm)))
                {
                    if (alg != FtpHashAlgorithm.NONE && cl.HashAlgorithms.HasFlag(alg))
                    {
                        FtpHash hash = null;

                        await cl.SetHashAlgorithmAsync(alg);

                        hash = await cl.GetHashAsync("LICENSE.TXT");

                        if (hash.IsValid)
                        {
                            Debug.Assert(hash.Verify(@"C:\FTPTEST\LICENSE.TXT"), "The computed hash didn't match or the hash object was invalid!");
                        }
                    }
                }
            }
        }
예제 #3
0
        /// <summary>
        /// Retrieves a checksum of the given file using a checksumming method
        /// that the server supports, if any. The algorithm used goes in this order:
        /// 1. HASH command; server preferred algorithm. See FtpClient.SetHashAlgorithm()
        /// 2. MD5 / XMD5 commands
        /// 3. XSHA1 command
        /// 4. XSHA256 command
        /// 5. XSHA512 command
        /// 6. XCRC command
        /// </summary>
        /// <param name="client">FtpClient Object</param>
        /// <param name="path">Full or relative path of the file to checksum</param>
        /// <returns>FtpHash object containing the value and algorithm. Use the IsValid property to
        /// determine if this command was successfull. FtpCommandException's can be thrown from
        /// the underlying calls.</returns>
        /// <example><code source="..\Examples\GetChecksum.cs" lang="cs" /></example>
        public static FtpHash GetChecksum(this FtpClient client, string path) {
            if (client.HasFeature(FtpCapability.HASH)) {
                return client.GetHash(path);
            }
            else {
                FtpHash res = new FtpHash();

                if (client.HasFeature(FtpCapability.MD5)) {
                    res.Value = client.GetMD5(path);
                    res.Algorithm = FtpHashAlgorithm.MD5;
                }
                else if (client.HasFeature(FtpCapability.XMD5)) {
                    res.Value = client.GetXMD5(path);
                    res.Algorithm = FtpHashAlgorithm.MD5;
                }
                else if (client.HasFeature(FtpCapability.XSHA1)) {
                    res.Value = client.GetXSHA1(path);
                    res.Algorithm = FtpHashAlgorithm.SHA1;
                }
                else if (client.HasFeature(FtpCapability.XSHA256)) {
                    res.Value = client.GetXSHA256(path);
                    res.Algorithm = FtpHashAlgorithm.SHA256;
                }
                else if (client.HasFeature(FtpCapability.XSHA512)) {
                    res.Value = client.GetXSHA512(path);
                    res.Algorithm = FtpHashAlgorithm.SHA512;
                }
                else if (client.HasFeature(FtpCapability.XCRC)) {
                    res.Value = client.GetXCRC(path);
                    res.Algorithm = FtpHashAlgorithm.CRC;
                }

                return res;
            }
        }
예제 #4
0
        public static void GetChecksum()
        {
            using (var conn = new FtpClient("127.0.0.1", "ftptest", "ftptest")) {
                conn.Connect();

                FtpHash hash = conn.GetChecksum("/path/to/remote/file");

                // Make sure it returned a, to the best of our knowledge, valid
                // hash object. The commands for retrieving checksums are
                // non-standard extensions to the protocol so we have to
                // presume that the response was in a format understood by
                // FluentFTP and parsed correctly.
                //
                // In addition, there is no built-in support for verifying
                // CRC hashes. You will need to write you own or use a
                // third-party solution.
                if (hash.IsValid && hash.Algorithm != FtpHashAlgorithm.CRC)
                {
                    if (hash.Verify("/some/local/file"))
                    {
                        Console.WriteLine("The checksum's match!");
                    }
                }
            }
        }
예제 #5
0
        public static void GetChceksumExample()
        {
            FtpHash hash = null;

            using (FtpClient cl = new FtpClient()) {
                cl.Credentials = new NetworkCredential("user", "pass");
                cl.Host        = "some.ftpserver.on.the.internet.com";

                hash = cl.GetChecksum("/path/to/remote/file");
                // Make sure it returned a, to the best of our knowledge, valid
                // hash object. The commands for retrieving checksums are
                // non-standard extensions to the protocol so we have to
                // presume that the response was in a format understood by
                // FluentFTP and parsed correctly.
                //
                // In addition, there is no built-in support for verifying
                // CRC hashes. You will need to write you own or use a
                // third-party solution.
                if (hash.IsValid && hash.Algorithm != FtpHashAlgorithm.CRC)
                {
                    if (hash.Verify("/some/local/file"))
                    {
                        Console.WriteLine("The checksum's match!");
                    }
                }
            }
        }
예제 #6
0
 public Results(string filename, long size, DateTime time, FtpHash hash, bool successful)
 {
     FileName   = filename;
     Size       = size;
     Time       = time;
     Hash       = hash;
     Successful = successful;
 }
예제 #7
0
        protected virtual PackDownloadResult Download(Uri uri)
        {
            string path = Path.Combine(DownloadsDirectory.FullName, Path.GetFileName(uri.ToString()));

            if (uri.IsAbsoluteUri)
            {
                if (uri.Scheme.Equals("http") || uri.Scheme.Equals("https"))
                {
                    using (WebClient client = new WebClient())
                    {
                        client.DownloadFile(uri, path);
                        return(new PackDownloadResult(path, true));
                    }
                }
                else if (uri.Scheme.Equals("ftp") || uri.Scheme.Equals("ftps"))
                {
                    using FtpClient client = FtpClient.Connect(uri);

                    // Get the hash of the file, if supported.

                    string           hash = null;
                    FtpHashAlgorithm algo = FtpHashAlgorithm.NONE;

                    if (!client.HashAlgorithms.HasFlag(FtpHashAlgorithm.NONE))
                    {
                        // CRC32 is prefered due to its speed.
                        if (client.HashAlgorithms.HasFlag(FtpHashAlgorithm.CRC))
                        {
                            client.SetHashAlgorithm(FtpHashAlgorithm.CRC);
                        }

                        // Take the hash.
                        FtpHash ftpHash = client.GetChecksum(uri.AbsolutePath);
                        hash = ftpHash.Value;
                        algo = ftpHash.Algorithm;
                    }

                    // Download the file.
                }
            }
            else
            {
                string source = uri.ToString();

                if (File.Exists(source))
                {
                    File.Copy(source, path);
                    return(new PackDownloadResult(path, true));
                }
            }

            return(new PackDownloadResult(default(FileInfo), false));
        }
예제 #8
0
        //-----------------------------------------------------------------------------------------
        // NOTE! GetChecksum automatically uses the first available hash algorithm on the server,
        //		 and it should be used as far as possible instead of GetHash, GetMD5, GetSHA256...
        //-----------------------------------------------------------------------------------------

        public static void GetChecksum()
        {
            using (var conn = new FtpClient("127.0.0.1", "ftptest", "ftptest")) {
                conn.Connect();

                // Get a hash checksum for the file
                FtpHash hash = conn.GetChecksum("/path/to/remote/file");

                // Make sure it returned a valid hash object
                if (hash.IsValid)
                {
                    if (hash.Verify("/some/local/file"))
                    {
                        Console.WriteLine("The checksum's match!");
                    }
                }
            }
        }
예제 #9
0
        /// <summary>
        /// Retrieves a checksum of the given file using a checksumming method
        /// that the server supports, if any. The algorithm used goes in this order:
        /// 1. HASH command; server preferred algorithm. See FtpClient.SetHashAlgorithm()
        /// 2. MD5 / XMD5 commands
        /// 3. XSHA1 command
        /// 4. XSHA256 command
        /// 5. XSHA512 command
        /// 6. XCRC command
        /// </summary>
        /// <param name="client">FtpClient Object</param>
        /// <param name="path">Full or relative path of the file to checksum</param>
        /// <returns>FtpHash object containing the value and algorithm. Use the IsValid property to
        /// determine if this command was successfull. FtpCommandException's can be thrown from
        /// the underlying calls.</returns>
        /// <example><code source="..\Examples\GetChecksum.cs" lang="cs" /></example>
        public static FtpHash GetChecksum(this FtpClient client, string path)
        {
            if (client.HasFeature(FtpCapability.HASH))
            {
                return(client.GetHash(path));
            }
            else
            {
                FtpHash res = new FtpHash();

                if (client.HasFeature(FtpCapability.MD5))
                {
                    res.Value     = client.GetMD5(path);
                    res.Algorithm = FtpHashAlgorithm.MD5;
                }
                else if (client.HasFeature(FtpCapability.XMD5))
                {
                    res.Value     = client.GetXMD5(path);
                    res.Algorithm = FtpHashAlgorithm.MD5;
                }
                else if (client.HasFeature(FtpCapability.XSHA1))
                {
                    res.Value     = client.GetXSHA1(path);
                    res.Algorithm = FtpHashAlgorithm.SHA1;
                }
                else if (client.HasFeature(FtpCapability.XSHA256))
                {
                    res.Value     = client.GetXSHA256(path);
                    res.Algorithm = FtpHashAlgorithm.SHA256;
                }
                else if (client.HasFeature(FtpCapability.XSHA512))
                {
                    res.Value     = client.GetXSHA512(path);
                    res.Algorithm = FtpHashAlgorithm.SHA512;
                }
                else if (client.HasFeature(FtpCapability.XCRC))
                {
                    res.Value     = client.GetXCRC(path);
                    res.Algorithm = FtpHashAlgorithm.CRC;
                }

                return(res);
            }
        }
예제 #10
0
        private async Task <String> Ftp2Async()
        {
            FtpClient client = new FtpClient();

            client.Host        = "localhost";
            client.Credentials = new NetworkCredential("makihara", "wildgeese");

            await client.ConnectAsync();

            //get a list of files and dir
            foreach (FtpListItem item in await client.GetListingAsync("/Fuji"))
            {
                //if this is a file
                if (item.Type == FtpFileSystemObjectType.File)
                {
                    //get the file size
                    long size = await client.GetFileSizeAsync(item.FullName);

                    //calculate a hash for the file on the server side (default algorithm)
                    FtpHash hash = await client.GetChecksumAsync(item.FullName);
                }

                //get modified date/time of the file or folder
                DateTime time = await client.GetModifiedTimeAsync(item.FullName);
            }
            client.Disconnect();

            return("aa");

            /*
             * client.Connect();
             *
             * //upload a file
             * client.UploadFile(@"UpdateCommon.inf", "/updateCommon.inf");
             *
             * //rename the uploaded file
             * client.Rename("/updateCommon.inf", "bb.inf");
             *
             * //download the file
             * client.DownloadFile(@"load.inf", "/bb.inf");
             *
             * client.Disconnect();
             */
        }
예제 #11
0
        /// <summary>
        /// Parses the recieved FTP hash response into a new FtpHash object.
        /// </summary>
        public static FtpHash Parse(string reply)
        {
            // Current draft says the server should return this:
            //		SHA-256 0-49 169cd22282da7f147cb491e559e9dd filename.ext

            // Current version of FileZilla returns this:
            //		SHA-1 21c2ca15cf570582949eb59fb78038b9c27ffcaf

            // Real reply that was failing:
            //		213 MD5 0-170500096 3197bf4ec5fa2d441c0f50264ca52f11


            var hash = new FtpHash();

            // FIX #722 - remove the FTP status code causing a wrong hash to be returned
            if (reply.StartsWith("2") && reply.Length > 10)
            {
                reply = reply.Substring(4);
            }

            Match m;

            if (!(m = Regex.Match(reply,
                                  @"(?<algorithm>.+)\s" +
                                  @"(?<bytestart>\d+)-(?<byteend>\d+)\s" +
                                  @"(?<hash>.+)\s" +
                                  @"(?<filename>.+)")).Success)
            {
                m = Regex.Match(reply, @"(?<algorithm>.+)\s(?<hash>.+)\s");
            }

            if (m != null && m.Success)
            {
                hash.Algorithm = HashAlgorithms.FromString(m.Groups["algorithm"].Value);
                hash.Value     = m.Groups["hash"].Value;
            }
            else
            {
                // failed to parse
            }

            return(hash);
        }
예제 #12
0
        public static async Task GetChecksumAsync()
        {
            var token = new CancellationToken();

            using (var conn = new FtpClient("127.0.0.1", "ftptest", "ftptest")) {
                await conn.ConnectAsync(token);

                // Get a hash checksum for the file
                FtpHash hash = await conn.GetChecksumAsync("/path/to/remote/file", token);

                // Make sure it returned a valid hash object
                if (hash.IsValid)
                {
                    if (hash.Verify("/some/local/file"))
                    {
                        Console.WriteLine("The checksum's match!");
                    }
                }
            }
        }
예제 #13
0
        public async Task <string> GetCheckSumAsync(string path, string fileName, FtpHashAlgorithm algorithm)
        {
            try
            {
                string result = string.Empty;

                FtpHash remoteHash = await _ftpClient.GetChecksumAsync(path + fileName);

                if (remoteHash.IsValid)
                {
                    result = remoteHash.Value;
                }

                return(result);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
예제 #14
0
        public void Test()
        {
            // create an FTP client
            FtpClient client = new FtpClient("123.123.123.123");

            //using (var conn = new FtpClient())
            //{

            //    conn.Host = "localhost";

            //    conn.Credentials = new NetworkCredential("ftptest", "ftptest");

            //    conn.Connect();

            //}


            // if you don't specify login credentials, we use the "anonymous" user account
            client.Credentials = new NetworkCredential("david", "pass123");

            // begin connecting to the server
            client.Connect();

            // get a list of files and directories in the "/htdocs" folder
            foreach (FtpListItem item in client.GetListing("/htdocs"))
            {
                // if this is a file
                if (item.Type == FtpFileSystemObjectType.File)
                {
                    // get the file size
                    long size = client.GetFileSize(item.FullName);
                }

                // get modified date/time of the file or folder
                DateTime time = client.GetModifiedTime(item.FullName);

                // calculate a hash for the file on the server side (default algorithm)
                FtpHash hash = client.GetHash(item.FullName);
            }

            // upload a file
            client.UploadFile(@"C:\MyVideo.mp4", "/htdocs/MyVideo.mp4");


            // rename the uploaded file
            client.Rename("/htdocs/MyVideo.mp4", "/htdocs/MyVideo_2.mp4");

            // download the file again
            client.DownloadFile(@"C:\MyVideo_2.mp4", "/htdocs/MyVideo_2.mp4");

            // delete the file
            client.DeleteFile("/htdocs/MyVideo_2.mp4");

            // delete a folder recursively
            client.DeleteDirectory("/htdocs/extras/");

            // check if a file exists
            if (client.FileExists("/htdocs/big2.txt"))
            {
            }

            // check if a folder exists
            if (client.DirectoryExists("/htdocs/extras/"))
            {
            }

            // upload a file and retry 3 times before giving up
            client.RetryAttempts = 3;
            client.UploadFile(@"C:\MyVideo.mp4", "/htdocs/big.txt", FtpExists.Overwrite, false, FtpVerify.Retry);

            // disconnect! good bye!
            client.Disconnect();
        }
예제 #15
0
        public void serviceCheckingFile()
        {
            string server          = ConfigurationManager.AppSettings["server"];
            string userName        = ConfigurationManager.AppSettings["userName"];
            string password        = ConfigurationManager.AppSettings["password"];
            string fileName        = ConfigurationManager.AppSettings["fileName"];
            string fullName        = ConfigurationManager.AppSettings["fullName"];
            string destinationName = ConfigurationManager.AppSettings["destinationName"];
            string sourceName      = ConfigurationManager.AppSettings["sourceName"];


            FtpClient client = new FtpClient(server);

            client.Credentials = new NetworkCredential(userName, password);
            client.Connect();
            //client.UploadFile(@fullName, destinationName + fileName);

            Log.Info("--------------------------------");
            Log.Info("FILE FROM SERVER:");
            // get a list of files and directories in the "/ftp" folder
            foreach (FtpListItem item in client.GetListing(destinationName))
            {
                // if this is a file
                if (item.Type == FtpFileSystemObjectType.File)
                {
                    Log.Info(item);


                    // get the file size
                    long size = client.GetFileSize(item.FullName);

                    // calculate a hash for the file on the server side (default algorithm)
                    FtpHash hash = client.GetChecksum(item.FullName);
                }

                // get modified date/time of the file or folder
                DateTime time = client.GetModifiedTime(item.FullName);
            }

            string[] filePaths = Directory.GetFiles(@sourceName);

            Log.Info("--------------------------------");
            Log.Info("FILE FROM LOCAL: (Matched with Server)");
            int count = 1;

            foreach (String item in filePaths)
            {
                string localFile = item.Replace(sourceName, "");

                foreach (FtpListItem itemA in client.GetListing(destinationName))
                {
                    if (itemA.Type == FtpFileSystemObjectType.File)
                    {
                        if (localFile.Equals(itemA.Name))
                        {
                            Log.Info(count + ")" + itemA.Name);
                            client.UploadFile(sourceName + localFile, destinationName + localFile);
                            count++;
                        }
                    }
                }
            }
            compressfile(sourceName);
            client.Disconnect();
        }