Ejemplo n.º 1
0
        /// <summary>
        /// Opens a data stream using the format and mode specified
        /// </summary>
        /// <param name="type">Type of data channel to use</param>
        /// <returns>Data Stream Object</returns>
        public FtpDataStream OpenDataStream(FtpDataType type)
        {
            FtpDataStream stream = null;

            this.SetDataType(type);

            switch (this.DataChannelType)
            {
            case FtpDataChannelType.Passive:
            case FtpDataChannelType.ExtendedPassive:
                stream = new FtpPassiveStream(this);
                break;

            case FtpDataChannelType.Active:
            case FtpDataChannelType.ExtendedActive:
                stream = new FtpActiveStream(this);
                break;
            }

            if (stream != null)
            {
                stream.ReadTimeout = this.DataChannelReadTimeout;
            }

            return(stream);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Opens the specified file for appending. Please call GetReply() after you have successfully transfered the file to read the "OK" command sent by the server and prevent stale data on the socket.
        /// </summary>
        /// <param name="path">The full or relative path to the file to be opened</param>
        /// <param name="type">ASCII/Binary</param>
        /// <returns>A stream for writing to the file on the server</returns>
        /// <example><code source="..\Examples\OpenAppend.cs" lang="cs" /></example>
        public virtual Stream OpenAppend(string path, FtpDataType type)
        {
            FtpTrace.WriteFunc("OpenAppend", new object[] { path, type });

            FtpClient     client = null;
            FtpDataStream stream = null;
            long          length = 0;

            lock (m_lock) {
                if (m_threadSafeDataChannels)
                {
                    client = CloneConnection();
                    client.Connect();
                    client.SetWorkingDirectory(GetWorkingDirectory());
                }
                else
                {
                    client = this;
                }

                client.SetDataType(type);
                length = client.GetFileSize(path);
                stream = client.OpenDataStream(("APPE " + path.GetFtpPath()), 0);

                if (length > 0 && stream != null)
                {
                    stream.SetLength(length);
                    stream.SetPosition(length);
                }
            }

            return(stream);
        }
Ejemplo n.º 3
0
        /// <summary>Internal method that handles actually setting the data type.</summary>
        /// <exception cref="FtpCommandException">Thrown when a FTP Command error condition occurs.</exception>
        /// <exception cref="FtpException">Thrown when a FTP error condition occurs.</exception>
        /// <param name="type">ASCII/Binary.</param>
        /// <remarks>This method doesn't do any locking to prevent recursive lock scenarios.  Callers must do their own locking.</remarks>
        private void SetDataTypeInternal(FtpDataType type)
        {
            FtpReply reply;

            switch (type)
            {
            case FtpDataType.ASCII:
                if (!(reply = Execute("TYPE A")).Success)
                {
                    throw new FtpCommandException(reply);
                }

                /*if (!(reply = Execute("STRU R")).Success)
                 *      FtpTrace.WriteLine(reply.Message);*/
                break;

            case FtpDataType.Binary:
                if (!(reply = Execute("TYPE I")).Success)
                {
                    throw new FtpCommandException(reply);
                }

                /*if (!(reply = Execute("STRU F")).Success)
                 *      FtpTrace.WriteLine(reply.Message);*/
                break;

            default:
                throw new FtpException("Unsupported data type: " + type.ToString());
            }
        }
Ejemplo n.º 4
0
 /// <summary>
 /// Sets the data type of information sent over the data stream asynchronously
 /// </summary>
 /// <param name="type">ASCII/Binary</param>
 protected async Task SetDataTypeAsync(FtpDataType type)
 {
     //TODO:  Rewrite as true async method with cancellation support
     await Task.Factory.FromAsync <FtpDataType>(
         (t, ac, s) => BeginSetDataType(t, ac, s),
         ar => EndSetDataType(ar),
         type, null);
 }
Ejemplo n.º 5
0
 /// <summary>
 /// Opens the specified file to be appended asynchronously
 /// </summary>
 /// <param name="path">Full or relative path of the file</param>
 /// <param name="type">ASCII/Binary</param>
 /// <returns>A stream for writing to the file on the server</returns>
 public async Task <Stream> OpenAppendAsync(string path, FtpDataType type)
 {
     //TODO:  Rewrite as true async method with cancellation support
     return(await Task.Factory.FromAsync <string, FtpDataType, Stream>(
                (p, t, ac, s) => BeginOpenAppend(p, t, ac, s),
                ar => EndOpenAppend(ar),
                path, type, null));
 }
        /// <summary>
        /// Sets the data type of information sent over the data stream
        /// </summary>
        /// <param name="type">ASCII/Binary</param>
        public async Task SetDataTypeAsync(FtpDataType type)
        {
            FtpResponse reply;

            if (!(reply = await m_Stream.SetDataTypeAsync(type)).Success)
            {
                throw new FtpCommandException(reply);
            }
        }
        /// <summary>
        /// Opens the specified file for reading
        /// </summary>
        /// <param name="path">The full or relative path of the file</param>
        /// <param name="type">ASCII/Binary</param>
        /// <param name="restart">Resume location</param>
        /// <returns>A stream for reading the file on the server</returns>
        public async Task <IInputStream> OpenReadAsync(string path, FtpDataType type = FtpDataType.Binary, long restart = 0)
        {
            await SetWorkingDirectoryAsync(path.GetFtpDirectoryName());

            await SetDataTypeAsync(type);

            var stream = await OpenDataStreamAsync(new FtpRetrieveRequest(path));

            return(stream.InputStream);
        }
        /// <summary>
        /// Opens the specified file for writing
        /// </summary>
        /// <param name="path">Full or relative path of the file</param>
        /// <param name="type">ASCII/Binary</param>
        /// <returns>A stream for writing to the file on the server</returns>
        public async Task <IOutputStream> OpenWriteAsync(string path, FtpDataType type = FtpDataType.Binary)
        {
            await SetWorkingDirectoryAsync(path.GetFtpDirectoryName());

            await SetDataTypeAsync(type);

            var stream = await OpenDataStreamAsync(new FtpStoreRequest(path));

            return(stream.OutputStream);
        }
Ejemplo n.º 9
0
 public bool Put(string local, string remote, FtpDataType fileType)
 {
     remote = bankroot + "/" + remote;
     byte[] buffer = File.ReadAllBytes(local);
     using (Stream ostream = client.OpenWrite(remote, fileType)) {
         ostream.Write(buffer, 0, buffer.Length);
         ostream.Close();
     }
     return true;
 }
Ejemplo n.º 10
0
        /// <summary>
        /// Begins an asynchronous operation to set the data type of information sent over the data stream
        /// </summary>
        /// <param name="type">ASCII/Binary</param>
        /// <param name="callback">Async callback</param>
        /// <param name="state">State object</param>
        /// <returns>IAsyncResult</returns>
        protected IAsyncResult BeginSetDataType(FtpDataType type, AsyncCallback callback, object state)
        {
            IAsyncResult ar;
            AsyncSetDataType func;

            ar = (func = new AsyncSetDataType(SetDataType)).BeginInvoke(type, callback, state);
            lock (m_asyncmethods) {
                m_asyncmethods.Add(ar, func);
            }

            return(ar);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Begins an asynchronous operation to open the specified file for reading
        /// </summary>
        /// <param name="path">The full or relative path of the file</param>
        /// <param name="type">ASCII/Binary</param>
        /// <param name="restart">Resume location</param>
        /// <param name="callback">Async Callback</param>
        /// <param name="state">State object</param>
        /// <returns>IAsyncResult</returns>
        /// <example><code source="..\Examples\BeginOpenRead.cs" lang="cs" /></example>
        public IAsyncResult BeginOpenRead(string path, FtpDataType type, long restart, AsyncCallback callback, object state)
        {
            AsyncOpenRead func;
            IAsyncResult ar;

            ar = (func = new AsyncOpenRead(OpenRead)).BeginInvoke(path, type, restart, callback, state);
            lock (m_asyncmethods) {
                m_asyncmethods.Add(ar, func);
            }

            return(ar);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Begins an asynchronous operation to open the specified file for appending
        /// </summary>
        /// <param name="path">Full or relative path of the file</param>
        /// <param name="type">ASCII/Binary</param>
        /// <param name="callback">Async callback</param>
        /// <param name="state">State object</param>
        /// <returns>IAsyncResult</returns>
        /// <example><code source="..\Examples\BeginOpenAppend.cs" lang="cs" /></example>
        public IAsyncResult BeginOpenAppend(string path, FtpDataType type, AsyncCallback callback, object state)
        {
            IAsyncResult ar;
            AsyncOpenAppend func;

            ar = (func = new AsyncOpenAppend(OpenAppend)).BeginInvoke(path, type, callback, state);
            lock (m_asyncmethods) {
                m_asyncmethods.Add(ar, func);
            }

            return(ar);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Sets the data type of information sent over the data stream
        /// </summary>
        /// <param name="type">ASCII/Binary</param>
        protected void SetDataType(FtpDataType type)
        {
#if !CORE14
            lock (m_lock) {
#endif
            this.SetDataTypeInternal(type);
#if !CORE14
        }
#endif

            CurrentDataType = type;
        }
Ejemplo n.º 14
0
        /// FTPサーバーへTYPEコマンドを送信します。
        /// <summary>
        /// Send type command to ftp server.
        /// FTPサーバーへTYPEコマンドを送信します。
        /// <param name="mode">形式オプション</param>
        /// <returns></returns>
        public FtpCommandResult ExecuteType(FtpDataType type)
        {
            switch (type)
            {
            case FtpDataType.Image: return(this.Execute("Type I"));

            case FtpDataType.Ebcdic: throw new NotImplementedException();

            case FtpDataType.Ascii: return(this.Execute("Type A"));

            default: throw new FtpClientException();
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Opens the specified file for reading
        /// </summary>
        /// <param name="path">The full or relative path of the file</param>
        /// <param name="type">ASCII/Binary</param>
        /// <param name="restart">Resume location</param>
        /// <returns>A stream for reading the file on the server</returns>
        /// <example><code source="..\Examples\OpenRead.cs" lang="cs" /></example>
        public virtual Stream OpenRead(string path, FtpDataType type, long restart)
        {
            // verify args
            if (path.IsBlank())
            {
                throw new ArgumentException("Required parameter is null or blank.", "path");
            }

            FtpTrace.WriteFunc("OpenRead", new object[] { path, type, restart });

            FtpClient     client = null;
            FtpDataStream stream = null;
            long          length = 0;

#if !CORE14
            lock (m_lock) {
#endif
            if (m_threadSafeDataChannels)
            {
                client = CloneConnection();
                client.Connect();
                client.SetWorkingDirectory(GetWorkingDirectory());
            }
            else
            {
                client = this;
            }

            client.SetDataType(type);
            length = client.GetFileSize(path);
            stream = client.OpenDataStream(("RETR " + path.GetFtpPath()), restart);
#if !CORE14
        }
#endif

            if (stream != null)
            {
                if (length > 0)
                {
                    stream.SetLength(length);
                }

                if (restart > 0)
                {
                    stream.SetPosition(restart);
                }
            }

            return(stream);
        }
Ejemplo n.º 16
0
 internal RunDTP_SO(int timeout,
                    string cmd,
                    FtpDataType dataType,
                    long restart,
                    DTPStream userStream,
                    AsyncCallback cb,
                    object state) : base(cb, state)
 {
     _timeout    = timeout;
     _command    = cmd;
     _userStream = userStream;
     _restart    = restart;
     _dataType   = dataType;
 }
Ejemplo n.º 17
0
 public bool Get(string local, string remote, FtpDataType fileType)
 {
     remote = bankroot + "/" + remote;
     Stream ostream = File.Create(local);
     byte[] buffer = new byte[1024];
     int bytesRead = 0; Console.WriteLine(remote);
     using (Stream istream = client.OpenRead(remote, fileType)) {
         while ((bytesRead = istream.Read(buffer, 0, buffer.Length)) != 0) {
             ostream.Write(buffer, 0, bytesRead);
             ostream.Flush();
         }
         ostream.Close();
         istream.Close();
     }
     return true;
 }
Ejemplo n.º 18
0
        internal IAsyncResult BeginExecute(int timeout,
                                           string command,
                                           FtpDataType dataType,
                                           long restart,
                                           DTPStream userStream,
                                           AsyncCallback cb,
                                           object state)
        {
            RunDTP_SO stateObj = new RunDTP_SO(timeout,
                                               command,
                                               dataType,
                                               restart,
                                               userStream,
                                               cb,
                                               state);

            SetProgress(true);
            _currentDC = null;
            try
            {
                //----------------------------------------
                //Lock Control connection to prevent
                //run the command like abort, quit, stat
                //during configuring of data connection
                _cc.BeginLock(Timeout.Infinite,
                              new WaitOrTimerCallback(LockFirst_End),
                              stateObj);
            }
            catch (Exception e)
            {
                SetProgress(false);
                CheckDisposed();

                NSTrace.WriteLineError(_errMsg + e.ToString());
                throw;
            }
            catch
            {
                SetProgress(false);
                CheckDisposed();

                NSTrace.WriteLineError(_errMsgNonCls + Environment.StackTrace.ToString());
                throw;
            }
            return(stateObj);
        }
Ejemplo n.º 19
0
        static void DoUpload(FtpClient cl, string root, string s)
        {
            FtpDataType type = FtpDataType.Binary;
            string      path = Path.GetDirectoryName(s).Replace(root, "");
            string      name = Path.GetFileName(s);

            if (Path.GetExtension(s).ToLower() == ".cs" || Path.GetExtension(s).ToLower() == ".txt")
            {
                type = FtpDataType.ASCII;
            }

            if (!cl.DirectoryExists(path))
            {
                cl.CreateDirectory(path, true);
            }
            else if (cl.FileExists(string.Format("{0}/{1}", path, name)))
            {
                cl.DeleteFile(string.Format("{0}/{1}", path, name));
            }

            using (
                Stream istream = new FileStream(s, FileMode.Open, FileAccess.Read),
                ostream = cl.OpenWrite(s.Replace(root, ""), type)) {
                byte[] buf  = new byte[8192];
                int    read = 0;

                try {
                    while ((read = istream.Read(buf, 0, buf.Length)) > 0)
                    {
                        ostream.Write(buf, 0, read);
                    }
                }
                finally {
                    ostream.Close();
                    istream.Close();
                }

                if (cl.HashAlgorithms != FtpHashAlgorithm.NONE)
                {
                    Debug.Assert(cl.GetHash(s.Replace(root, "")).Verify(s), "The computed hashes don't match!");
                }
            }

            /*if (!cl.GetHash(s.Replace(root, "")).Verify(s))
             *  throw new Exception("Hashes didn't match!");*/
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Set the data type for the data channel
        /// </summary>
        /// <param name="datatype"></param>
        protected void SetDataType(FtpDataType datatype)
        {
            switch (datatype)
            {
            case FtpDataType.Binary:
                this.Execute("TYPE I");
                break;

            case FtpDataType.ASCII:
                this.Execute("TYPE A");
                break;
            }

            if (!this.ResponseStatus)
            {
                throw new FtpCommandException(this);
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Opens the specified file for writing. Please call GetReply() after you have successfully transfered the file to read the "OK" command sent by the server and prevent stale data on the socket.
        /// </summary>
        /// <param name="path">Full or relative path of the file</param>
        /// <param name="type">ASCII/Binary</param>
        /// <param name="checkIfFileExists">Only set this to false if you are SURE that the file does not exist. If true, it reads the file size and saves it into the stream length.</param>
        /// <returns>A stream for writing to the file on the server</returns>
        /// <example><code source="..\Examples\OpenWrite.cs" lang="cs" /></example>
        public virtual Stream OpenWrite(string path, FtpDataType type, bool checkIfFileExists)
        {
            // verify args
            if (path.IsBlank())
            {
                throw new ArgumentException("Required parameter is null or blank.", "path");
            }

            FtpTrace.WriteFunc("OpenWrite", new object[] { path, type });

            FtpClient client     = null;
            FtpDataStream stream = null;
            long length          = 0;

#if !CORE14
            lock (m_lock) {
#endif
            if (m_threadSafeDataChannels)
            {
                client = CloneConnection();
                client.Connect();
                client.SetWorkingDirectory(GetWorkingDirectory());
            }
            else
            {
                client = this;
            }

            client.SetDataType(type);
            length = checkIfFileExists ? client.GetFileSize(path) : 0;
            stream = client.OpenDataStream(("STOR " + path.GetFtpPath()), 0);

            if (length > 0 && stream != null)
            {
                stream.SetLength(length);
            }
#if !CORE14
        }
#endif

            return(stream);
        }
Ejemplo n.º 22
0
        string GetTypeCommand(FtpDataType dataType)
        {
            string typeCmd = "TYPE ";

            if (FtpDataType.Ascii == dataType)
            {
                typeCmd += "A";
            }
            else if (FtpDataType.Binary == dataType)
            {
                typeCmd += "I";
            }
            else
            {
                string msg = string.Format("Data type is unsupported ({0}).", dataType.ToString());
                NSTrace.WriteLineError(msg);
                throw new NotSupportedException(msg);
            }
            return(typeCmd);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Sets the data type of information sent over the data stream
        /// </summary>
        /// <param name="type">ASCII/Binary</param>
        protected void SetDataType(FtpDataType type)
        {
            FtpReply reply;

#if !CORE14
            lock (m_lock) {
#endif
            switch (type)
            {
            case FtpDataType.ASCII:
                if (!(reply = Execute("TYPE A")).Success)
                {
                    throw new FtpCommandException(reply);
                }

                /*if (!(reply = Execute("STRU R")).Success)
                 *      FtpTrace.WriteLine(reply.Message);*/
                break;

            case FtpDataType.Binary:
                if (!(reply = Execute("TYPE I")).Success)
                {
                    throw new FtpCommandException(reply);
                }

                /*if (!(reply = Execute("STRU F")).Success)
                 *      FtpTrace.WriteLine(reply.Message);*/
                break;

            default:
                throw new FtpException("Unsupported data type: " + type.ToString());
            }
#if !CORE14
        }
#endif

            CurrentDataType = type;
        }
 /// <summary>
 /// Opens the specified file to be appended to
 /// </summary>
 /// <param name="path">The full or relative path to the file to be opened</param>
 /// <param name="type">ASCII/Binary</param>
 /// <returns>A stream for writing to the file on the server</returns>
 public async Task <IOutputStream> OpenAppendAsync(string path, FtpDataType type = FtpDataType.Binary)
 {
     // TODO: Implement OpenReadAsync
     throw new NotImplementedException();
 }
Ejemplo n.º 25
0
        internal void Execute(int timeout,
                              string cmd,
                              FtpDataType dataType,
                              long restart,
                              DTPStream userStream)
        {
            bool ccLocked = false;

            //protected component against simultaneuous usage
            SetProgress(true);
            try
            {
                //----------------------------------------
                //Lock Control connection to prevent
                //run the command like abort, quit, stat
                //during configuring of data connection
                ccLocked = _cc.Lock(Timeout.Infinite);

                FtpResponse response = null;
                //----------------------------------------
                //send transfser type command
                if ((false == _client.IsDataTypeWasCached) ||
                    ((true == _client.IsDataTypeWasCached) && (_client.CachedDataType != dataType)))
                {
                    string typeCmd = GetTypeCommand(dataType);
                    response = _cc.SendCommandEx(timeout, typeCmd);
                    FtpClient.CheckCompletionResponse(response);

                    _client.IsDataTypeWasCached = true;
                    _client.CachedDataType      = dataType;
                }

                //----------------------------------------
                //Initialize data connection
                _currentDC = null;
                Cmd_GetDataConnection getDC = new Cmd_GetDataConnection(_client);
                lock (this)
                {
                    if (!_disposed)
                    {
                        _currentDC = getDC.Execute(timeout);
                    }
                }
                CheckDisposed();

                //----------------------------------------
                //send restart position, if needed
                if (0 < restart)
                {
                    string restCmd = "REST " + restart.ToString();
                    response = _cc.SendCommandEx(timeout, restCmd);
                    if (false == response.IsIntermediateReply)
                    {
                        throw GetRestartNotSuppException(response);
                    }
                    CheckDisposed();
                }

                //----------------------------------------
                //establish connection now, if it is outbound
                if (FtpDataConnectionType.Outbound == _currentDC.Type)
                {
                    _currentDC.Establish(timeout);
                    CheckDisposed();
                }

                //----------------------------------------
                //send transfer request to the server
                response = _cc.SendCommandEx(timeout, cmd);
                CheckDisposed();

                //----------------------------------------
                //first respone should be one
                //of the 1** - let's check it
                if (response.IsCompletionReply)                 //should not happen
                {
                    NSTrace.WriteLineError("Executing DTP: receive completion as first reply.");
                    //_currentDC.AbortAsyncEstablish();
                }
                else
                {
                    FtpClient.CheckPreliminaryResponse(response);

                    //----------------------------------------
                    //establish connection now, if it is inbound
                    if (FtpDataConnectionType.Inbound == _currentDC.Type)
                    {
                        _currentDC.Establish(timeout);
                        CheckDisposed();
                    }

                    FtpAbortedException abortEx = null;
                    try
                    {
                        //----------------------------------------
                        //subscribe to data events
                        _currentDC.DataTransfered += new FtpDataConnection.DataTransferedEventHandler(OnDataTransfered);
                        _currentDC.Completed      += new FtpDataConnection.CompletedEventHandler(OnCompleted);

                        //----------------------------------------
                        //prepare for abortion
                        _aborted           = false;
                        _client.CurrentDTP = this;

                        //----------------------------------------
                        //Unlock control connection, now the command
                        //like abort, stat, quit could be issued
                        ccLocked = false;
                        _cc.Unlock();

                        //----------------------------------------
                        //start DTP
                        _currentDC.RunDTPStream(timeout, userStream);
                    }
                    catch (FtpAbortedException ex)
                    {
                        abortEx = ex;
                    }
                    finally
                    {
                        _currentDC.DataTransfered -= new FtpDataConnection.DataTransferedEventHandler(OnDataTransfered);
                        _currentDC.Completed      -= new FtpDataConnection.CompletedEventHandler(OnCompleted);
                    }

                    //----------------------------------------
                    //Lock control connection again - reading
                    //responses
                    ccLocked = _cc.Lock(Timeout.Infinite);

                    //----------------------------------------
                    //Skip preliminary responses
                    //
                    for (int i = 0; i < 10; i++)
                    {
                        response = _cc.ReadResponse(timeout);
                        CheckDisposed();
                        if (response.IsPreliminaryReply)
                        {
                            continue;
                        }
                        break;
                    }

                    //----------------------------------------
                    //If still receiving priliminary responses
                    //then it looks suspecious?
                    //
                    if (response.IsPreliminaryReply)
                    {
                        throw GetTooManyRespException();
                    }

                    //----------------------------------------
                    // Dealing with Abort or Reset
                    //
                    if (!_aborted && (null == abortEx))
                    {
                        if (!_currentDC.ManuallyClosed)
                        {
                            FtpClient.CheckCompletionResponse(response);
                        }
                        else
                        {
                            //----------------------------------------
                            //we DID close the data connection,
                            //so, in general, the response should be
                            //errorneous - therefore skip checking of it
                        }
                    }
                    else
                    {
                        if (null != abortEx)                        //&& !response.IsCompletionReply)
                        {
                            abortEx.SetResponse(response);
                        }

                        //----------------------------------------
                        //If "ABOR" command was sent we need to
                        //one more response...
                        //
                        if (_aborted)
                        {
                            response = _cc.ReadResponse(timeout);
                        }
                    }

                    //------------------------------------------
                    //If "QUIT" was sent during data transfer
                    //then here we need read one more response
                    if (_quited)
                    {
                        response = _cc.ReadResponse(timeout);
                    }

                    if (null != abortEx)
                    {
                        throw abortEx;
                    }
                }
            }
            catch (Exception e)
            {
                CheckDisposed();
                NSTrace.WriteLineError(_errMsg + e.ToString());
                throw;
            }
            catch
            {
                CheckDisposed();
                NSTrace.WriteLineError(_errMsgNonCls + Environment.StackTrace.ToString());
                throw;
            }
            finally
            {
                SetProgress(false);
                _client.CurrentDTP = null;

                if (true == ccLocked)
                {
                    _cc.Unlock();
                }
            }
        }
Ejemplo n.º 26
0
 /// <summary>
 /// Downloads a file from the server
 /// </summary>
 /// <param name="remote">Remote path of the file</param>
 /// <param name="local">Local path of the file</param>
 /// <param name="datatype">ASCII/Binary</param>
 /// <param name="rest">Resume location</param>
 /// <example>
 ///     <code source="..\Examples\Download\Program.cs" lang="cs"></code>
 /// </example>
 public void Download(string remote, string local, FtpDataType datatype, long rest) {
     this.Download(new FtpFile(this, remote), local, datatype, rest);
 }
Ejemplo n.º 27
0
 /// <summary>
 /// Downloads a file from the server
 /// </summary>
 /// <param name="remote">Remote path of the file</param>
 /// <param name="local">Local path of the file</param>
 /// <param name="datatype">ASCII/Binary</param>
 /// <example>
 ///     <code source="..\Examples\Download\Program.cs" lang="cs"></code>
 /// </example>
 public void Download(string remote, string local, FtpDataType datatype) {
     this.Download(remote, local, datatype, 0);
 }
Ejemplo n.º 28
0
 /// <summary>
 /// Opens a file for writing. If you want the file size, be sure to retrieve
 /// it before attempting to open a file on the server.
 /// </summary>
 /// <param name="path">The full or relative (to the current working directory) path</param>
 /// <param name="datatype">ASCII/Binary</param>
 /// <returns>FtpDataChannel used for reading the data stream. Be sure to disconnect when finished.</returns>
 public FtpDataStream OpenWrite(string path, FtpDataType datatype) {
     return this.OpenWrite(path, datatype, 0);
 }
Ejemplo n.º 29
0
        /// <summary>
        /// Uploads a stream to the specified remote file
        /// </summary>
        /// <param name="istream"></param>
        /// <param name="remote"></param>
        /// <param name="datatype"></param>
        /// <param name="rest"></param>
        /// <example>
        ///     <code source="..\Examples\Upload\Program.cs" lang="cs"></code>
        /// </example>
        public void Upload(Stream istream, FtpFile remote, FtpDataType datatype, long rest) {
            long size = 0;
            long total = 0;
            int read = 0;

            if (istream == null) {
                throw new ArgumentException("istream is null");
            }

            if (remote == null) {
                throw new ArgumentException("remote is null");
            }

            if (!istream.CanRead) {
                throw new ArgumentException("istream is not readable");
            }

            if (istream.CanSeek) {
                size = istream.Length;

                if (rest > 0) { // set resume position
                    istream.Seek(rest, SeekOrigin.Begin);
                    total = rest;
                }
            }
            else {
                rest = 0;
            }

            using (FtpDataStream ch = this.OpenWrite(remote.FullName, datatype, rest)) {
                byte[] buf = new byte[ch.SendBufferSize];
                DateTime start = DateTime.Now;
                FtpTransferInfo e;

                while ((read = istream.Read(buf, 0, buf.Length)) > 0) {
                    ch.Write(buf, 0, read);
                    total += read;
                    e = new FtpTransferInfo(FtpTransferType.Upload, remote.FullName, size, rest, total, start, false);

                    this.OnTransferProgress(e);
                    if (e.Cancel) {
                        break;
                    }
                }

                // fire one more time to let event handler know the transfer is complete
                this.OnTransferProgress(new FtpTransferInfo(FtpTransferType.Upload, remote.FullName,
                    size, rest, total, start, true));
            }
        }
Ejemplo n.º 30
0
 /// <summary>
 /// Uploads a file to the server
 /// </summary>
 /// <param name="istream">The stream to upload</param>
 /// <param name="remote">Remote path of the file</param>
 /// <param name="datatype">ASCII/Binary</param>
 /// <example>
 ///     <code source="..\Examples\Upload\Program.cs" lang="cs"></code>
 /// </example>
 public void Upload(Stream istream, FtpFile remote, FtpDataType datatype) {
     this.Upload(istream, remote, datatype, 0);
 }
Ejemplo n.º 31
0
		/// <summary>
		/// Uploads the specified file
		/// </summary>
		/// <param name="local"></param>
		/// <param name="datatype"></param>
		public void Upload(string local, FtpDataType datatype) {
			this.Client.Upload(local, this, datatype);
		}
Ejemplo n.º 32
0
 public override Stream OpenAppend(string path, FtpDataType type)
 {
     return(base.OpenAppend(_root + path, type));
 }
Ejemplo n.º 33
0
 public override Stream OpenRead(string path, FtpDataType type, long restart)
 {
     return(base.OpenRead(_root + path, type, restart));
 }
Ejemplo n.º 34
0
		/// <summary>
		/// Uploads the specified file
		/// </summary>
		/// <param name="local"></param>
		/// <param name="datatype"></param>
		/// <param name="rest"></param>
		public void Upload(string local, FtpDataType datatype, long rest) {
			this.Client.Upload(local, this, datatype, rest);
		}
Ejemplo n.º 35
0
 public FtpSetDataTypeRequest(FtpDataType type) : base("TYPE")
 {
     Arguments    = new string[1];
     Arguments[0] = type == FtpDataType.ASCII ? "A" : "I";
 }
Ejemplo n.º 36
0
		/// <summary>
		/// Opens this file for reading
		/// </summary>
		/// <param name="mode"></param>
		/// <param name="rest"></param>
		/// <returns></returns>
		public FtpDataStream OpenRead(FtpDataType mode, long rest) {
			return this.Client.OpenRead(this.FullName, mode, rest);
		}
Ejemplo n.º 37
0
 /// <summary>
 /// Uploads a file to the server
 /// </summary>
 /// <param name="remote">Remote path of the file</param>
 /// <param name="local">Local path of the file</param>
 /// <param name="datatype">ASCII/Binary</param>
 /// <example>
 ///     <code source="..\Examples\Upload\Program.cs" lang="cs"></code>
 /// </example>
 public void Upload(string local, FtpFile remote, FtpDataType datatype) {
     this.Upload(local, remote, datatype, 0);
 }
Ejemplo n.º 38
0
		/// <summary>
		/// Opens this file for reading
		/// </summary>
		/// <param name="mode"></param>
		/// <returns></returns>
		public FtpDataStream OpenRead(FtpDataType mode) {
			return this.OpenRead(mode, 0);
		}
Ejemplo n.º 39
0
 /// <summary>
 /// Uploads a file to the server
 /// </summary>
 /// <param name="remote">Local path of the file</param>
 /// <param name="local">Remote path of the file</param>
 /// <param name="datatype">ASCII/Binary</param>
 /// <param name="rest">Resume location</param>
 /// <example>
 ///     <code source="..\Examples\Upload\Program.cs" lang="cs"></code>
 /// </example>
 public void Upload(string local, FtpFile remote, FtpDataType datatype, long rest) {
     using (FileStream istream = new FileStream(local, FileMode.Open, FileAccess.Read)) {
         try {
             this.Upload(istream, remote, datatype, rest);
         }
         finally {
             istream.Close();
         }
     }
 }
        /// <summary>
        /// Opens a data stream using the format and mode specified
        /// </summary>
        /// <param name="type">Type of data channel to use</param>
        /// <returns>Data Stream Object</returns>
        public FtpDataStream OpenDataStream(FtpDataType type) {
            FtpDataStream stream = null;

            this.SetDataType(type);

            switch (this.DataChannelType) {
                case FtpDataChannelType.Passive:
                case FtpDataChannelType.ExtendedPassive:
                    stream = new FtpPassiveStream(this);
                    break;
                case FtpDataChannelType.Active:
                case FtpDataChannelType.ExtendedActive:
                    stream = new FtpActiveStream(this);
                    break;
            }

            if (stream != null) {
                stream.ReadTimeout = this.DataChannelReadTimeout;
            }

            return stream;
        }
Ejemplo n.º 41
0
        /// <summary>
        /// Opens a file for reading. If you want the file size, be sure to retrieve
        /// it before attempting to open a file on the server.
        /// </summary>
        /// <param name="path">The full or relative (to the current working directory) path</param>
        /// <param name="datatype">ASCII/Binary</param>
        /// <param name="rest">Resume location, if specified and server doesn't support REST STREAM, a NotImplementedException is thrown</param>
        /// <returns>FtpDataChannel used for reading the data stream. Be sure to disconnect when finished.</returns>
        public FtpDataStream OpenRead(string path, FtpDataType datatype, long rest) {
            FtpDataStream s = this.OpenDataStream(datatype);

            if (rest > 0) {
                s.Seek(rest);
            }

            if (!s.Execute("RETR {0}", path)) {
                s.Dispose();
                throw new FtpCommandException(this);
            }

            return s;
        }
Ejemplo n.º 42
0
		/// <summary>
		/// Download this file
		/// </summary>
		/// <param name="local">Local path</param>
		/// <param name="datatype">ASCII/Binary</param>
		/// <param name="rest">Restart location</param>
		public void Download(string local, FtpDataType datatype, long rest) {
			this.Client.Download(this, local, datatype, rest);
		}
Ejemplo n.º 43
0
        /// <summary>
        /// Opens a file for writing. If you want the existing file size, be sure to retrieve
        /// it before attempting to open a file on the server.
        /// </summary>
        /// <param name="path">The full or relative (to the current working directory) path</param>
        /// <param name="datatype">ASCII/Binary</param>
        /// <param name="rest">Resume location, if specified and server doesn't support REST STREAM, a NotImplementedException is thrown</param>
        /// <returns>FtpDataChannel used for reading the data stream. Be sure to disconnect when finished.</returns>
        public FtpDataStream OpenWrite(string path, FtpDataType datatype, long rest) {
            FtpDataStream s = this.OpenDataStream(datatype);
            string cmd = null;

            if (rest > 0 && this.System == "Windows_NT") {
                this.WriteLineToLogStream("IIS servers do not support REST + STOR. The rest parament will be ignored and the file will be appended to.");
                cmd = string.Format("APPE {0}", path);
            }
            else {
                if (rest > 0) {
                    s.Seek(rest);
                }

                cmd = string.Format("STOR {0}", path);
            }

            if (!s.Execute(cmd)) {
                s.Dispose();
                throw new FtpCommandException(this);
            }

            return s;
        }
Ejemplo n.º 44
0
        /// <summary>
        /// Opens the specified file for writing
        /// </summary>
        /// <param name="path">Full or relative path of the file</param>
        /// <param name="type">ASCII/Binary</param>
        /// <returns>A stream for writing to the file on the server</returns>
        public async Task<IOutputStream> OpenWriteAsync(string path, FtpDataType type = FtpDataType.Binary)
        {
            await SetWorkingDirectoryAsync(path.GetFtpDirectoryName());

            await SetDataTypeAsync(type);

            var stream = await OpenDataStreamAsync(new FtpStoreRequest(path));

            return stream.OutputStream;
        }
Ejemplo n.º 45
0
 /// <summary>
 /// Downloads a file from the server
 /// </summary>
 /// <param name="remote">Remote path of the file</param>
 /// <param name="ostream">The stream to download the file to</param>
 /// <param name="datatype">ASCII/Binary</param>
 /// <example>
 ///     <code source="..\Examples\Download\Program.cs" lang="cs"></code>
 /// </example>
 public void Download(string remote, Stream ostream, FtpDataType datatype) {
     this.Download(new FtpFile(this, remote), ostream, datatype, 0);
 }
Ejemplo n.º 46
0
 /// <summary>
 /// Opens the specified file for reading
 /// </summary>
 /// <param name="path">The full or relative path of the file</param>
 /// <param name="type">ASCII/Binary</param>
 /// <returns>A stream for reading the file on the server</returns>
 /// <example><code source="..\Examples\OpenRead.cs" lang="cs" /></example>
 public Stream OpenRead(string path, FtpDataType type)
 {
     return(OpenRead(path, type, 0));
 }
Ejemplo n.º 47
0
 public Task <FtpResponse> SetDataTypeAsync(FtpDataType dataType)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 48
0
 /// <summary>
 /// Opens the specified file to be appended to
 /// </summary>
 /// <param name="path">The full or relative path to the file to be opened</param>
 /// <param name="type">ASCII/Binary</param>
 /// <returns>A stream for writing to the file on the server</returns>
 public async Task<IOutputStream> OpenAppendAsync(string path, FtpDataType type = FtpDataType.Binary)
 {
     // TODO: Implement OpenReadAsync
     throw new NotImplementedException();
 }
Ejemplo n.º 49
0
 /// <summary>
 /// Downloads a file from the server
 /// </summary>
 /// <param name="remote">Remote path of the file</param>
 /// <param name="ostream">The stream to download the file to</param>
 /// <param name="datatype">ASCII/Binary</param>
 /// <example>
 ///     <code source="..\Examples\Download\Program.cs" lang="cs"></code>
 /// </example>
 public void Download(FtpFile remote, Stream ostream, FtpDataType datatype) {
     this.Download(remote, ostream, datatype, 0);
 }
Ejemplo n.º 50
0
 /// <summary>
 /// Downloads the specified file from the server
 /// </summary>
 /// <param name="remote"></param>
 /// <param name="local"></param>
 /// <param name="datatype"></param>
 /// <param name="rest"></param>
 /// <example>
 ///     <code source="..\Examples\Download\Program.cs" lang="cs"></code>
 /// </example>
 public void Download(FtpFile remote, string local, FtpDataType datatype, long rest) {
     using (FileStream ostream = new FileStream(local, FileMode.OpenOrCreate, FileAccess.Write)) {
         try {
             this.Download(remote, ostream, datatype, rest);
         }
         finally {
             ostream.Close();
         }
     }
 }
Ejemplo n.º 51
0
        /// <summary>
        /// Opens the specified file for reading
        /// </summary>
        /// <param name="path">The full or relative path of the file</param>
        /// <param name="type">ASCII/Binary</param>
        /// <param name="restart">Resume location</param>
        /// <returns>A stream for reading the file on the server</returns>
        public async Task<IInputStream> OpenReadAsync(string path, FtpDataType type = FtpDataType.Binary,
            long restart = 0)
        {
            await SetWorkingDirectoryAsync(path.GetFtpDirectoryName());

            await SetDataTypeAsync(type);

            var stream = await OpenDataStreamAsync(new FtpRetrieveRequest(path));

            return stream.InputStream;
        }
Ejemplo n.º 52
0
        /// <summary>
        /// Downloads the remote file to the specified stream
        /// </summary>
        /// <param name="remote"></param>
        /// <param name="ostream"></param>
        /// <param name="datatype"></param>
        /// <param name="rest"></param>
        /// <example>
        ///     <code source="..\Examples\Download\Program.cs" lang="cs"></code>
        /// </example>
        public void Download(FtpFile remote, Stream ostream, FtpDataType datatype, long rest) {
            long size = remote.Length;
            long total = 0;
            int read = 0;

            if (remote == null) {
                throw new ArgumentException("remote is null");
            }

            if (ostream == null) {
                throw new ArgumentException("ostream is null");
            }

            if (!ostream.CanWrite) {
                throw new ArgumentException("ostream is not writable");
            }

            if (rest > 0 && ostream.CanSeek) { // set reset position
                ostream.Seek(rest, SeekOrigin.Begin);
                total = rest;
            }
            else if (!ostream.CanSeek) {
                rest = 0;
            }

            try {
                using (FtpDataStream ch = this.OpenRead(remote.FullName, datatype, rest)) {
                    byte[] buf = new byte[ch.ReceiveBufferSize];
                    DateTime start = DateTime.Now;
                    FtpTransferInfo e = null;

                    while ((read = ch.Read(buf, 0, buf.Length)) > 0) {
                        ostream.Write(buf, 0, read);
                        total += read;
                        e = new FtpTransferInfo(FtpTransferType.Download, remote.FullName, size, rest, total, start, false);

                        this.OnTransferProgress(e);
                        if (e.Cancel) {
                            break;
                        }
                    }

                    // fire one more time to let event handler know that the transfer is complete
                    this.OnTransferProgress(new FtpTransferInfo(FtpTransferType.Download, remote.FullName,
                        size, rest, total, start, true));
                }
            }
            finally {
                ostream.Flush();
            }
        }
Ejemplo n.º 53
0
 /// <summary>
 /// Opens the specified file for reading
 /// </summary>
 /// <param name="path">The full or relative path of the file</param>
 /// <param name="type">ASCII/Binary</param>
 /// <param name="callback">Async Callback</param>
 /// <param name="state">State object</param>
 /// <returns>IAsyncResult</returns>
 /// <example><code source="..\Examples\BeginOpenRead.cs" lang="cs" /></example>
 public IAsyncResult BeginOpenRead(string path, FtpDataType type, AsyncCallback callback, object state)
 {
     return(BeginOpenRead(path, type, 0, callback, state));
 }
Ejemplo n.º 54
0
 /// <summary>
 /// Uploads a file to the server
 /// </summary>
 /// <param name="istream">The stream to read the file from</param>
 /// <param name="remote">Remote path of the file</param>
 /// <param name="datatype">ASCII/Binary</param>
 /// <example>
 ///     <code source="..\Examples\Upload\Program.cs" lang="cs"></code>
 /// </example>
 public void Upload(Stream istream, string remote, FtpDataType datatype) {
     this.Upload(istream, new FtpFile(this, remote), datatype, 0);
 }
Ejemplo n.º 55
0
        /// <summary>
        /// Sets the data type of information sent over the data stream
        /// </summary>
        /// <param name="type">ASCII/Binary</param>
        public async Task SetDataTypeAsync(FtpDataType type)
        {
            FtpResponse reply;

            if (!(reply = await m_Stream.SetDataTypeAsync(type)).Success)
                throw new FtpCommandException(reply);
        }
Ejemplo n.º 56
0
 /// <summary>
 /// Uploads a file to the server
 /// </summary>
 /// <param name="remote">Local path of the file</param>
 /// <param name="local">Remote path of the file</param>
 /// <param name="datatype">ASCII/Binary</param>
 /// <param name="rest">Resume location</param>
 /// <example>
 ///     <code source="..\Examples\Upload\Program.cs" lang="cs"></code>
 /// </example>
 public void Upload(string local, string remote, FtpDataType datatype, long rest) {
     this.Upload(local, new FtpFile(this, remote), datatype, rest);
 }
Ejemplo n.º 57
0
 public FtpSetDataTypeRequest(FtpDataType type)
     : base("TYPE")
 {
     Arguments = new string[1];
     Arguments[0] = type == FtpDataType.ASCII ? "A" : "I";
 }
Ejemplo n.º 58
0
		/// <summary>
		/// Opens this file for writing
		/// </summary>
		/// <param name="mode"></param>
		/// <returns></returns>
		public FtpDataStream OpenWrite(FtpDataType mode) {
			return this.OpenWrite(mode, 0);
		}
Ejemplo n.º 59
0
 /// FTPサーバーへTYPEコマンドを送信します。
 /// <summary>
 /// Send type command to ftp server.
 /// FTPサーバーへTYPEコマンドを送信します。
 /// <param name="mode">形式オプション</param>
 /// <returns></returns>
 public Task <FtpCommandResult> ExecuteTypeAsync(FtpDataType type)
 {
     return(CreateNewTask <FtpCommandResult>(() => this.ExecuteType(type)));
 }
        /// <summary>
        /// Set the data type for the data channel
        /// </summary>
        /// <param name="datatype"></param>
        protected void SetDataType(FtpDataType datatype) {
            switch (datatype) {
                case FtpDataType.Binary:
                    this.Execute("TYPE I");
                    break;
                case FtpDataType.ASCII:
                    this.Execute("TYPE A");
                    break;
            }

            if (!this.ResponseStatus) {
                throw new FtpCommandException(this);
            }
        }