Example #1
0
        static void StreamResponses()
        {
            using (FtpClient cl = new FtpClient()) {
                cl.Credentials          = new NetworkCredential(m_user, m_pass);
                cl.Host                 = m_host;
                cl.EncryptionMode       = FtpEncryptionMode.None;
                cl.ValidateCertificate += new FtpSslValidation(delegate(FtpClient control, FtpSslValidationEventArgs e) {
                    e.Accept = true;
                });

                using (FtpDataStream s = (FtpDataStream)cl.OpenWrite("test.txt")) {
                    FtpReply r = s.CommandStatus;

                    Console.WriteLine();
                    Console.WriteLine("Response to STOR:");
                    Console.WriteLine("Code: {0}", r.Code);
                    Console.WriteLine("Message: {0}", r.Message);
                    Console.WriteLine("Informational: {0}", r.InfoMessages);

                    r = s.Close();
                    Console.WriteLine();
                    Console.WriteLine("Response after close:");
                    Console.WriteLine("Code: {0}", r.Code);
                    Console.WriteLine("Message: {0}", r.Message);
                    Console.WriteLine("Informational: {0}", r.InfoMessages);
                }
            }
        }
Example #2
0
        //[Fact]
        public async Task StreamResponsesAsync()
        {
            using (FtpClient cl = NewFtpClient())
            {
                cl.EncryptionMode       = FtpEncryptionMode.None;
                cl.ValidateCertificate += OnValidateCertificate;

                using (FtpDataStream s = (FtpDataStream)await cl.OpenWriteAsync("test.txt"))
                {
                    FtpReply r = s.CommandStatus;

                    FtpTrace.WriteLine("");
                    FtpTrace.WriteLine("Response to STOR:");
                    FtpTrace.WriteLine("Code: " + r.Code);
                    FtpTrace.WriteLine("Message: " + r.Message);
                    FtpTrace.WriteLine("Informational: " + r.InfoMessages);

                    r = s.Close();
                    FtpTrace.WriteLine("");
                    FtpTrace.WriteLine("Response after close:");
                    FtpTrace.WriteLine("Code: " + r.Code);
                    FtpTrace.WriteLine("Message: " + r.Message);
                    FtpTrace.WriteLine("Informational: " + r.InfoMessages);
                }
            }
        }
Example #3
0
        /// <summary>
        /// Send file to remote. Only FTP supported at present
        /// </summary>
        /// <param name="file"></param>
        /// <param name="source"></param>
        /// <returns></returns>
        public static bool UploadFile(Uri file, string source)
        {
            try
            {
                string[] userInfo = file.UserInfo.Split(new[] { ':' });
                if (userInfo.Length != 2)
                {
                    Logger.Warn("No login information in URL!");
                    return(false);
                }

                using (var cl = new FtpClient(userInfo[0], userInfo[1], file.Host))
                {
                    string remoteFile = file.PathAndQuery;

                    // Check for existence
                    if (!File.Exists(source))
                    {
                        return(false);
                    }

                    long size = new FileInfo(source).Length;

                    using (FtpDataStream chan = cl.OpenWrite(remoteFile))
                    {
                        using (var stream = new FileStream(source, FileMode.Open))
                        {
                            using (var reader = new BinaryReader(stream))
                            {
                                var  buf = new byte[cl.SendBufferSize];
                                int  read;
                                long total = 0;

                                while ((read = reader.Read(buf, 0, buf.Length)) > 0)
                                {
                                    total += read;

                                    chan.Write(buf, 0, read);

                                    Logger.DebugFormat("\rUploaded: {0}/{1} {2:p2}",
                                                       total, size, (total / (double)size));
                                }
                            }
                        }
                        // when Dispose() is called on the chan object, the data channel
                        // stream will automatically be closed
                    }
                    // when Dispose() is called on the cl object, a logout will
                    // automatically be performed and the socket will be closed.
                }
            }
            catch (Exception e)
            {
                Logger.Warn("Exception uploading file:" + e.Message);
                return(false);
            }
            return(true);
        }
Example #4
0
        /// <summary>
        /// Get remote file. Only FTP supported at present
        /// </summary>
        /// <param name="file"></param>
        /// <param name="destination"></param>
        /// <returns></returns>
        public static bool DownloadFile(Uri file, string destination)
        {
            try
            {
                string[] userInfo = file.UserInfo.Split(new[] { ':' });
                if (userInfo.Length != 2)
                {
                    Logger.Warn("No login information in URL!");
                    return(false);
                }

                using (var cl = new FtpClient(userInfo[0], userInfo[1], file.Host))
                {
                    string remoteFile = file.PathAndQuery;

                    // Check for existence
#warning DOESN'T SEEM TO WORK ON ALL SERVERS
//                    if (!cl.FileExists(remoteFile))
//                        return false;

                    long size = cl.GetFileSize(remoteFile);

                    using (FtpDataStream chan = cl.OpenRead(remoteFile))
                    {
                        using (var stream = new FileStream(destination, FileMode.Create))
                        {
                            using (var writer = new BinaryWriter(stream))
                            {
                                var  buf = new byte[cl.ReceiveBufferSize];
                                int  read;
                                long total = 0;

                                while ((read = chan.Read(buf, 0, buf.Length)) > 0)
                                {
                                    total += read;

                                    writer.Write(buf, 0, read);

                                    Logger.DebugFormat("\rDownloaded: {0}/{1} {2:p2}",
                                                       total, size, (total / (double)size));
                                }
                            }
                        }
                        // when Dispose() is called on the chan object, the data channel
                        // stream will automatically be closed
                    }
                    // when Dispose() is called on the cl object, a logout will
                    // automatically be performed and the socket will be closed.
                }
            }
            catch (Exception e)
            {
                Logger.Warn("Exception downloading file:" + e.Message);
                return(false);
            }
            return(true);
        }
		internal FtpWebResponse( FtpDataStream stream )
		{
			dataStream = stream;
		}
		private void OpenActiveDataConnection()
		{
			Socket dataSocket = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
			IPHostEntry localhostEntry = Dns.GetHostByName( Dns.GetHostName() );
			IPEndPoint listener = new IPEndPoint( localhostEntry.AddressList[0], 0 );
			dataSocket.Bind( listener );
			dataSocket.Listen( 5 );
			IPEndPoint localEP = (IPEndPoint)dataSocket.LocalEndPoint;
			UInt32 localEPAddress = (UInt32) localEP.Address.Address;
			string local = FormatAddress( localEPAddress, localEP.Port );
			CommandResponse response = SendCommand( "PORT", local );
			dataStream = new FtpDataStream( dataSocket );
		}
		private void OpenPassiveDataConnection()
		{
			CommandResponse response = SendCommand( "PASV", null );
			if( response.Status != 227 )
				throw new ApplicationException( "Couldn't open passive data connection, no DataConnection IP was given" );

			// TODO Use this IP instead of the same as the communication ip
			string ip = GetIP( response );
			int port = GetPort( response );

			Socket dataSocket = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
			IPHostEntry serverHostEntry = Dns.GetHostByName( uri.Host );
			IPEndPoint	serverEndPoint = new IPEndPoint( serverHostEntry.AddressList[0], port );
			dataSocket.Connect( serverEndPoint );
			dataStream = new FtpDataStream( dataSocket );
		}