| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353 | using System;using System.Linq;using System.Collections.Generic;using System.IO;using Renci.SshNet.Sftp;using System.Text;using Renci.SshNet.Common;using System.Globalization;using System.Threading;using System.Diagnostics.CodeAnalysis;namespace Renci.SshNet{    /// <summary>    /// Implementation of the SSH File Transfer Protocol (SFTP) over SSH.    /// </summary>    public partial class SftpClient : BaseClient    {        /// <summary>        /// Holds SftpSession instance that used to communicate to the SFTP server        /// </summary>        private SftpSession _sftpSession;        private bool _disposeConnectionInfo;        /// <summary>        /// Gets or sets the operation timeout.        /// </summary>        /// <value>The operation timeout.</value>        public TimeSpan OperationTimeout { get; set; }        /// <summary>        /// Gets or sets the size of the buffer.        /// </summary>        /// <value>The size of the buffer.</value>        public uint BufferSize { get; set; }        /// <summary>        /// Gets remote working directory.        /// </summary>        public string WorkingDirectory        {            get            {                if (this._sftpSession == null)                    return null;                return this._sftpSession.WorkingDirectory;            }        }        /// <summary>        /// Gets sftp protocol version.        /// </summary>        public int ProtocolVersion { get; private set; }        #region Constructors        /// <summary>        /// Initializes a new instance of the <see cref="SftpClient"/> class.        /// </summary>        /// <param name="connectionInfo">The connection info.</param>        /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is <b>null</b>.</exception>        public SftpClient(ConnectionInfo connectionInfo)            : base(connectionInfo)        {            this.OperationTimeout = new TimeSpan(0, 0, 0, 0, -1);            this.BufferSize = 1024 * 32 - 52;        }        /// <summary>        /// Initializes a new instance of the <see cref="SftpClient"/> class.        /// </summary>        /// <param name="host">Connection host.</param>        /// <param name="port">Connection port.</param>        /// <param name="username">Authentication username.</param>        /// <param name="password">Authentication password.</param>        /// <exception cref="ArgumentNullException"><paramref name="password"/> is <b>null</b>.</exception>        /// <exception cref="ArgumentException"><paramref name="host"/> is invalid. <para>-or-</para> <paramref name="username"/> is <b>null</b> or contains whitespace characters.</exception>        /// <exception cref="ArgumentOutOfRangeException"><paramref name="port"/> is not within <see cref="System.Net.IPEndPoint.MinPort"/> and <see cref="System.Net.IPEndPoint.MaxPort"/>.</exception>        [SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope", Justification = "Disposed in Dispose(bool) method.")]        public SftpClient(string host, int port, string username, string password)            : this(new PasswordConnectionInfo(host, port, username, password))        {            this._disposeConnectionInfo = true;        }        /// <summary>        /// Initializes a new instance of the <see cref="SftpClient"/> class.        /// </summary>        /// <param name="host">Connection host.</param>        /// <param name="username">Authentication username.</param>        /// <param name="password">Authentication password.</param>        /// <exception cref="ArgumentNullException"><paramref name="password"/> is <b>null</b>.</exception>        /// <exception cref="ArgumentException"><paramref name="host"/> is invalid. <para>-or-</para> <paramref name="username"/> is <b>null</b> contains whitespace characters.</exception>        public SftpClient(string host, string username, string password)            : this(host, 22, username, password)        {        }        /// <summary>        /// Initializes a new instance of the <see cref="SftpClient"/> class.        /// </summary>        /// <param name="host">Connection host.</param>        /// <param name="port">Connection port.</param>        /// <param name="username">Authentication username.</param>        /// <param name="keyFiles">Authentication private key file(s) .</param>        /// <exception cref="ArgumentNullException"><paramref name="keyFiles"/> is <b>null</b>.</exception>        /// <exception cref="ArgumentException"><paramref name="host"/> is invalid. <para>-or-</para> <paramref name="username"/> is nu<b>null</b>ll or contains whitespace characters.</exception>        /// <exception cref="ArgumentOutOfRangeException"><paramref name="port"/> is not within <see cref="System.Net.IPEndPoint.MinPort"/> and <see cref="System.Net.IPEndPoint.MaxPort"/>.</exception>        [SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope", Justification = "Disposed in Dispose(bool) method.")]        public SftpClient(string host, int port, string username, params PrivateKeyFile[] keyFiles)            : this(new PrivateKeyConnectionInfo(host, port, username, keyFiles))        {            this._disposeConnectionInfo = true;        }        /// <summary>        /// Initializes a new instance of the <see cref="SftpClient"/> class.        /// </summary>        /// <param name="host">Connection host.</param>        /// <param name="username">Authentication username.</param>        /// <param name="keyFiles">Authentication private key file(s) .</param>        /// <exception cref="ArgumentNullException"><paramref name="keyFiles"/> is <b>null</b>.</exception>        /// <exception cref="ArgumentException"><paramref name="host"/> is invalid. <para>-or-</para> <paramref name="username"/> is <b>null</b> or contains whitespace characters.</exception>        public SftpClient(string host, string username, params PrivateKeyFile[] keyFiles)            : this(host, 22, username, keyFiles)        {        }        #endregion        /// <summary>        /// Changes remote directory to path.        /// </summary>        /// <param name="path">New directory path.</param>        /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>        /// <exception cref="SshConnectionException">Client is not connected.</exception>        /// <exception cref="SftpPermissionDeniedException">Permission to change directory denied by remote host. <para>-or-</para> A SSH command was denied by the server.</exception>        /// <exception cref="SftpPathNotFoundException">The path in <paramref name="path"/> was not found on the remote host.</exception>        /// <exception cref="SshException">A SSH error where <see cref="P:SshException.Message"/> is the message from the remote host.</exception>        public void ChangeDirectory(string path)        {            if (path == null)                throw new ArgumentNullException("path");            //  Ensure that connection is established.            this.EnsureConnection();            this._sftpSession.ChangeDirectory(path);        }        /// <summary>        /// Changes permissions of file(s) to specified mode.        /// </summary>        /// <param name="path">File(s) path, may match multiple files.</param>        /// <param name="mode">The mode.</param>        /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>        /// <exception cref="SshConnectionException">Client is not connected.</exception>        /// <exception cref="SftpPermissionDeniedException">Permission to change permission on the path(s) was denied by the remote host. <para>-or-</para> A SSH command was denied by the server.</exception>        /// <exception cref="SftpPathNotFoundException">The path in <paramref name="path"/> was not found on the remote host.</exception>        /// <exception cref="SshException">A SSH error where <see cref="P:SshException.Message"/> is the message from the remote host.</exception>        public void ChangePermissions(string path, short mode)        {            var file = this.Get(path);            file.SetPermissions(mode);        }        /// <summary>        /// Creates remote directory specified by path.        /// </summary>        /// <param name="path">Directory path to create.</param>        /// <exception cref="ArgumentException"><paramref name="path"/> is <b>null</b> or contains whitespace characters.</exception>        /// <exception cref="SshConnectionException">Client is not connected.</exception>        /// <exception cref="Renci.SshNet.Common.SftpPermissionDeniedException">Permission to create the directory was denied by the remote host. <para>-or-</para> A SSH command was denied by the server.</exception>        /// <exception cref="Renci.SshNet.Common.SshException">A SSH error where <see cref="P:SshException.Message"/> is the message from the remote host.</exception>        public void CreateDirectory(string path)        {            if (path.IsNullOrWhiteSpace())                throw new ArgumentException(path);            //  Ensure that connection is established.            this.EnsureConnection();            var fullPath = this._sftpSession.GetCanonicalPath(path);            this._sftpSession.RequestMkDir(fullPath);        }        /// <summary>        /// Deletes remote directory specified by path.        /// </summary>        /// <param name="path">Directory to be deleted path.</param>        /// <exception cref="ArgumentException"><paramref name="path"/> is <b>null</b> or contains whitespace characters.</exception>        /// <exception cref="SshConnectionException">Client is not connected.</exception>        /// <exception cref="Renci.SshNet.Common.SftpPermissionDeniedException">Permission to delete the directory was denied by the remote host. <para>-or-</para> A SSH command was denied by the server.</exception>        /// <exception cref="Renci.SshNet.Common.SshException">A SSH error where <see cref="P:SshException.Message"/> is the message from the remote host.</exception>        public void DeleteDirectory(string path)        {            if (path.IsNullOrWhiteSpace())                throw new ArgumentException("path");            //  Ensure that connection is established.            this.EnsureConnection();            var fullPath = this._sftpSession.GetCanonicalPath(path);            this._sftpSession.RequestRmDir(fullPath);        }        /// <summary>        /// Deletes remote file specified by path.        /// </summary>        /// <param name="path">File to be deleted path.</param>        /// <exception cref="ArgumentException"><paramref name="path"/> is <b>null</b> or contains whitespace characters.</exception>        /// <exception cref="SshConnectionException">Client is not connected.</exception>        /// <exception cref="Renci.SshNet.Common.SftpPermissionDeniedException">Permission to delete the file was denied by the remote host. <para>-or-</para> A SSH command was denied by the server.</exception>        /// <exception cref="Renci.SshNet.Common.SshException">A SSH error where <see cref="P:SshException.Message"/> is the message from the remote host.</exception>        public void DeleteFile(string path)        {            if (path.IsNullOrWhiteSpace())                throw new ArgumentException("path");            //  Ensure that connection is established.            this.EnsureConnection();            var fullPath = this._sftpSession.GetCanonicalPath(path);            this._sftpSession.RequestRemove(fullPath);        }        /// <summary>        /// Renames remote file from old path to new path.        /// </summary>        /// <param name="oldPath">Path to the old file location.</param>        /// <param name="newPath">Path to the new file location.</param>        /// <exception cref="ArgumentNullException"><paramref name="oldPath"/> is <b>null</b>. <para>-or-</para> or <paramref name="newPath"/> is <b>null</b>.</exception>        /// <exception cref="SshConnectionException">Client is not connected.</exception>        /// <exception cref="Renci.SshNet.Common.SftpPermissionDeniedException">Permission to rename the file was denied by the remote host. <para>-or-</para> A SSH command was denied by the server.</exception>        /// <exception cref="Renci.SshNet.Common.SshException">A SSH error where <see cref="P:SshException.Message"/> is the message from the remote host.</exception>        public void RenameFile(string oldPath, string newPath)        {            if (oldPath == null)                throw new ArgumentNullException("oldPath");            if (newPath == null)                throw new ArgumentNullException("newPath");            //  Ensure that connection is established.            this.EnsureConnection();            var oldFullPath = this._sftpSession.GetCanonicalPath(oldPath);            var newFullPath = this._sftpSession.GetCanonicalPath(newPath);            this._sftpSession.RequestRename(oldFullPath, newFullPath);        }        /// <summary>        /// Creates a symbolic link from old path to new path.        /// </summary>        /// <param name="path">The old path.</param>        /// <param name="linkPath">The new path.</param>        /// <exception cref="ArgumentException"><paramref name="path"/> is <b>null</b>. <para>-or-</para> <paramref name="linkPath"/> is <b>null</b> or contains whitespace characters.</exception>        /// <exception cref="SshConnectionException">Client is not connected.</exception>        /// <exception cref="Renci.SshNet.Common.SftpPermissionDeniedException">Permission to create the symbolic link was denied by the remote host. <para>-or-</para> A SSH command was denied by the server.</exception>        /// <exception cref="Renci.SshNet.Common.SshException">A SSH error where <see cref="P:SshException.Message"/> is the message from the remote host.</exception>        public void SymbolicLink(string path, string linkPath)        {            if (path.IsNullOrWhiteSpace())                throw new ArgumentException("path");            if (linkPath.IsNullOrWhiteSpace())                throw new ArgumentException("linkPath");            //  Ensure that connection is established.            this.EnsureConnection();            var fullPath = this._sftpSession.GetCanonicalPath(path);            var linkFullPath = this._sftpSession.GetCanonicalPath(linkPath);            this._sftpSession.RequestSymLink(fullPath, linkFullPath);        }        /// <summary>        /// Retrieves list of files in remote directory.        /// </summary>        /// <param name="path">The path.</param>        /// <returns>List of directory entries</returns>        /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>        /// <exception cref="SshConnectionException">Client is not connected.</exception>        /// <exception cref="Renci.SshNet.Common.SftpPermissionDeniedException">Permission to list the contents of the directory was denied by the remote host. <para>-or-</para> A SSH command was denied by the server.</exception>        /// <exception cref="Renci.SshNet.Common.SshException">A SSH error where <see cref="P:SshException.Message"/> is the message from the remote host.</exception>        public IEnumerable<SftpFile> ListDirectory(string path)        {            return InternalListDirectory(path, null);        }        /// <summary>        /// Begins an asynchronous operation of retrieving list of files in remote directory.        /// </summary>        /// <param name="path">The path.</param>        /// <param name="asyncCallback">The method to be called when the asynchronous write operation is completed.</param>        /// <param name="state">A user-provided object that distinguishes this particular asynchronous write request from other requests.</param>        /// <returns>        /// An <see cref="IAsyncResult"/> that references the asynchronous operation.        /// </returns>        public IAsyncResult BeginListDirectory(string path, AsyncCallback asyncCallback, object state)        {            var asyncResult = new SftpListDirectoryAsyncResult(asyncCallback, state);            this.ExecuteThread(() =>            {                try                {                    var result = this.InternalListDirectory(path, asyncResult);                    asyncResult.SetAsCompleted(result, false);                }                catch (Exception exp)                {                    asyncResult.SetAsCompleted(exp, false);                }            });            return asyncResult;        }        /// <summary>        /// Ends an asynchronous operation of retrieving list of files in remote directory.        /// </summary>        /// <param name="asyncResult">The pending asynchronous SFTP request.</param>        /// <returns>        /// List of files        /// </returns>        /// <exception cref="ArgumentException">The IAsyncResult object (<paramref name="asyncResult"/>) did not come from the corresponding async method on this type. <para>-or-</para> EndExecute was called multiple times with the same IAsyncResult.</exception>        public IEnumerable<SftpFile> EndListDirectory(IAsyncResult asyncResult)        {            var ar = asyncResult as SftpListDirectoryAsyncResult;            if (ar == null || ar.EndInvokeCalled)                throw new ArgumentException("Either the IAsyncResult object did not come from the corresponding async method on this type, or EndExecute was called multiple times with the same IAsyncResult.");            // Wait for operation to complete, then return result or throw exception            return ar.EndInvoke();        }        /// <summary>        /// Gets reference to remote file or directory.        /// </summary>        /// <param name="path">The path.</param>        /// <returns></returns>        /// <exception cref="SshConnectionException">Client is not connected.</exception>        /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>        public SftpFile Get(string path)        {            if (path == null)                throw new ArgumentNullException("path");            //  Ensure that connection is established.            this.EnsureConnection();            var fullPath = this._sftpSession.GetCanonicalPath(path);            var attributes = this._sftpSession.RequestLStat(fullPath);            return new SftpFile(this._sftpSession, fullPath, attributes);        }        /// <summary>        /// Checks whether file pr directory exists;        /// </summary>        /// <param name="path">The path.</param>        /// <returns><c>true</c> if directory or file exists; otherwise <c>false</c>.</returns>        /// <exception cref="ArgumentException"><paramref name="path"/> is <b>null</b> or contains whitespace characters.</exception>        /// <exception cref="SshConnectionException">Client is not connected.</exception>        /// <exception cref="Renci.SshNet.Common.SftpPermissionDeniedException">Permission to perform the operation was denied by the remote host. <para>-or-</para> A SSH command was denied by the server.</exception>        /// <exception cref="Renci.SshNet.Common.SshException">A SSH error where <see cref="P:SshException.Message"/> is the message from the remote host.</exception>        public bool Exists(string path)        {            if (path.IsNullOrWhiteSpace())                throw new ArgumentException("path");            //  Ensure that connection is established.            this.EnsureConnection();            var fullPath = this._sftpSession.GetCanonicalPath(path);            //  Try to open as a file            var handle = this._sftpSession.RequestOpen(fullPath, Flags.Read, true);            if (handle == null)            {                handle = this._sftpSession.RequestOpenDir(fullPath, true);            }            if (handle == null)            {                return false;            }            else            {                this._sftpSession.RequestClose(handle);                return true;            }        }        /// <summary>        /// Downloads remote file specified by the path into the stream.        /// </summary>        /// <param name="path">File to download.</param>        /// <param name="output">Stream to write the file into.</param>        /// <exception cref="ArgumentNullException"><paramref name="output"/> is <b>null</b>.</exception>        /// <exception cref="ArgumentException"><paramref name="path"/> is <b>null</b> or contains whitespace characters.</exception>        /// <exception cref="SshConnectionException">Client is not connected.</exception>        /// <exception cref="Renci.SshNet.Common.SftpPermissionDeniedException">Permission to perform the operation was denied by the remote host. <para>-or-</para> A SSH command was denied by the server.</exception>        /// <exception cref="Renci.SshNet.Common.SshException">A SSH error where <see cref="P:SshException.Message"/> is the message from the remote host.</exception>        /// <remarks>Method calls made by this method to <paramref name="output"/>, may under certain conditions result in exceptions thrown by the stream.</remarks>        public void DownloadFile(string path, Stream output)        {            this.InternalDownloadFile(path, output, null);        }        /// <summary>        /// Begins an asynchronous file downloading into the stream.        /// </summary>        /// <param name="path">The path.</param>        /// <param name="output">The output.</param>        /// <param name="asyncCallback">The method to be called when the asynchronous write operation is completed.</param>        /// <param name="state">A user-provided object that distinguishes this particular asynchronous write request from other requests.</param>        /// <returns>An <see cref="IAsyncResult"/> that references the asynchronous operation.</returns>        /// <exception cref="ArgumentNullException"><paramref name="output"/> is <b>null</b>.</exception>        /// <exception cref="ArgumentException"><paramref name="path"/> is <b>null</b> or contains whitespace characters.</exception>        /// <exception cref="SshConnectionException">Client is not connected.</exception>        /// <exception cref="Renci.SshNet.Common.SftpPermissionDeniedException">Permission to perform the operation was denied by the remote host. <para>-or-</para> A SSH command was denied by the server.</exception>        /// <exception cref="Renci.SshNet.Common.SshException">A SSH error where <see cref="P:SshException.Message"/> is the message from the remote host.</exception>        /// <remarks>Method calls made by this method to <paramref name="output"/>, may under certain conditions result in exceptions thrown by the stream.</remarks>        public IAsyncResult BeginDownloadFile(string path, Stream output, AsyncCallback asyncCallback, object state)        {            if (path.IsNullOrWhiteSpace())                throw new ArgumentException("path");            if (output == null)                throw new ArgumentNullException("output");            //  Ensure that connection is established.            this.EnsureConnection();            var asyncResult = new SftpDownloadAsyncResult(asyncCallback, state);            this.ExecuteThread(() =>            {                try                {                    this.InternalDownloadFile(path, output, asyncResult);                    asyncResult.SetAsCompleted(null, false);                }                catch (Exception exp)                {                    asyncResult.SetAsCompleted(exp, false);                }            });            return asyncResult;        }        /// <summary>        /// Ends an asynchronous file downloading into the stream.        /// </summary>        /// <param name="asyncResult">The pending asynchronous SFTP request.</param>        /// <exception cref="ArgumentException">The IAsyncResult object (<paramref name="asyncResult"/>) did not come from the corresponding async method on this type. <para>-or-</para> EndExecute was called multiple times with the same IAsyncResult.</exception>        public void EndDownloadFile(IAsyncResult asyncResult)        {            var ar = asyncResult as SftpDownloadAsyncResult;            if (ar == null || ar.EndInvokeCalled)                throw new ArgumentException("Either the IAsyncResult object did not come from the corresponding async method on this type, or EndExecute was called multiple times with the same IAsyncResult.");            // Wait for operation to complete, then return result or throw exception            ar.EndInvoke();        }        /// <summary>        /// Uploads stream into remote file..        /// </summary>        /// <param name="input">Data input stream.</param>        /// <param name="path">Remote file path.</param>        /// <exception cref="ArgumentNullException"><paramref name="input"/> is <b>null</b>.</exception>        /// <exception cref="ArgumentException"><paramref name="path"/> is <b>null</b> or contains whitespace characters.</exception>        /// <exception cref="SshConnectionException">Client is not connected.</exception>        /// <exception cref="Renci.SshNet.Common.SftpPermissionDeniedException">Permission to upload the file was denied by the remote host. <para>-or-</para> A SSH command was denied by the server.</exception>        /// <exception cref="Renci.SshNet.Common.SshException">A SSH error where <see cref="P:SshException.Message"/> is the message from the remote host.</exception>        /// <remarks>Method calls made by this method to <paramref name="input"/>, may under certain conditions result in exceptions thrown by the stream.</remarks>        public void UploadFile(Stream input, string path)        {            this.UploadFile(input, path, true);        }        /// <summary>        /// Uploads stream into remote file..        /// </summary>        /// <param name="input">Data input stream.</param>        /// <param name="path">Remote file path.</param>        /// <param name="canOverride">if set to <c>true</c> then existing file will be overwritten.</param>        /// <exception cref="ArgumentNullException"><paramref name="input"/> is <b>null</b>.</exception>        /// <exception cref="ArgumentException"><paramref name="path"/> is <b>null</b> or contains whitespace characters.</exception>        /// <exception cref="SshConnectionException">Client is not connected.</exception>        /// <exception cref="Renci.SshNet.Common.SftpPermissionDeniedException">Permission to upload the file was denied by the remote host. <para>-or-</para> A SSH command was denied by the server.</exception>        /// <exception cref="Renci.SshNet.Common.SshException">A SSH error where <see cref="P:SshException.Message"/> is the message from the remote host.</exception>        /// <remarks>        /// Method calls made by this method to <paramref name="input"/>, may under certain conditions result in exceptions thrown by the stream.        /// </remarks>        public void UploadFile(Stream input, string path, bool canOverride)        {            var flags = Flags.Write | Flags.Truncate;            if (canOverride)                flags |= Flags.CreateNewOrOpen;            else                flags |= Flags.CreateNew;            this.InternalUploadFile(input, path, null, flags);        }        /// <summary>        /// Begins an asynchronous uploading the steam into remote file.        /// </summary>        /// <param name="input">Data input stream.</param>        /// <param name="path">Remote file path.</param>        /// <param name="asyncCallback">The method to be called when the asynchronous write operation is completed.</param>        /// <param name="state">A user-provided object that distinguishes this particular asynchronous write request from other requests.</param>        /// <returns>An <see cref="IAsyncResult"/> that references the asynchronous operation.</returns>        /// <exception cref="ArgumentNullException"><paramref name="input"/> is <b>null</b>.</exception>        /// <exception cref="ArgumentException"><paramref name="path"/> is <b>null</b> or contains whitespace characters.</exception>        /// <exception cref="SshConnectionException">Client is not connected.</exception>        /// <exception cref="Renci.SshNet.Common.SftpPermissionDeniedException">Permission to list the contents of the directory was denied by the remote host. <para>-or-</para> A SSH command was denied by the server.</exception>        /// <exception cref="Renci.SshNet.Common.SshException">A SSH error where <see cref="P:SshException.Message"/> is the message from the remote host.</exception>        /// <remarks>Method calls made by this method to <paramref name="input"/>, may under certain conditions result in exceptions thrown by the stream.</remarks>        public IAsyncResult BeginUploadFile(Stream input, string path, AsyncCallback asyncCallback, object state)        {            return this.BeginUploadFile(input, path, true, asyncCallback, state);        }        /// <summary>        /// Begins an asynchronous uploading the steam into remote file.        /// </summary>        /// <param name="input">Data input stream.</param>        /// <param name="path">Remote file path.</param>        /// <param name="canOverride">if set to <c>true</c> then existing file will be overwritten.</param>        /// <param name="asyncCallback">The method to be called when the asynchronous write operation is completed.</param>        /// <param name="state">A user-provided object that distinguishes this particular asynchronous write request from other requests.</param>        /// <returns>An <see cref="IAsyncResult"/> that references the asynchronous operation.</returns>        /// <exception cref="ArgumentNullException"><paramref name="input"/> is <b>null</b>.</exception>        /// <exception cref="ArgumentException"><paramref name="path"/> is <b>null</b> or contains whitespace characters.</exception>        /// <exception cref="SshConnectionException">Client is not connected.</exception>        /// <exception cref="Renci.SshNet.Common.SftpPermissionDeniedException">Permission to list the contents of the directory was denied by the remote host. <para>-or-</para> A SSH command was denied by the server.</exception>        /// <exception cref="Renci.SshNet.Common.SshException">A SSH error where <see cref="P:SshException.Message"/> is the message from the remote host.</exception>        /// <remarks>Method calls made by this method to <paramref name="input"/>, may under certain conditions result in exceptions thrown by the stream.</remarks>        public IAsyncResult BeginUploadFile(Stream input, string path, bool canOverride, AsyncCallback asyncCallback, object state)        {            if (input == null)                throw new ArgumentNullException("input");            if (path.IsNullOrWhiteSpace())                throw new ArgumentException("path");            var flags = Flags.Write | Flags.Truncate;            if (canOverride)                flags |= Flags.CreateNewOrOpen;            else                flags |= Flags.CreateNew;            //  Ensure that connection is established.            this.EnsureConnection();            var asyncResult = new SftpUploadAsyncResult(asyncCallback, state);            this.ExecuteThread(() =>            {                try                {                    this.InternalUploadFile(input, path, asyncResult, flags);                    asyncResult.SetAsCompleted(null, false);                }                catch (Exception exp)                {                    asyncResult.SetAsCompleted(exp, false);                }            });            return asyncResult;        }        /// <summary>        /// Ends an asynchronous uploading the steam into remote file.        /// </summary>        /// <param name="asyncResult">The pending asynchronous SFTP request.</param>        /// <exception cref="ArgumentException">The IAsyncResult object (<paramref name="asyncResult"/>) did not come from the corresponding async method on this type. <para>-or-</para> EndExecute was called multiple times with the same IAsyncResult.</exception>        public void EndUploadFile(IAsyncResult asyncResult)        {            var ar = asyncResult as SftpUploadAsyncResult;            if (ar == null || ar.EndInvokeCalled)                throw new ArgumentException("Either the IAsyncResult object did not come from the corresponding async method on this type, or EndExecute was called multiple times with the same IAsyncResult.");            // Wait for operation to complete, then return result or throw exception            ar.EndInvoke();        }        #region File Methods        /// <summary>        /// Appends lines to a file, and then closes the file.        /// </summary>        /// <param name="path">The file to append the lines to. The file is created if it does not already exist.</param>        /// <param name="contents">The lines to append to the file.</param>        /// <exception cref="ArgumentNullException"><paramref name="path"/> is<b>null</b> <para>-or-</para> <paramref name="contents"/> is <b>null</b>.</exception>        public void AppendAllLines(string path, IEnumerable<string> contents)        {            if (contents == null)                throw new ArgumentNullException("contents");            using (var stream = this.AppendText(path))            {                foreach (var line in contents)                {                    stream.WriteLine(line);                }            }        }        /// <summary>        /// Appends lines to a file by using a specified encoding, and then closes the file.        /// </summary>        /// <param name="path">The file to append the lines to. The file is created if it does not already exist.</param>        /// <param name="contents">The lines to append to the file.</param>        /// <param name="encoding">The character encoding to use.</param>        /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>. <para>-or-</para> <paramref name="contents"/> is <b>null</b>. <para>-or-</para> <paramref name="encoding"/> is <b>null</b>.</exception>        public void AppendAllLines(string path, IEnumerable<string> contents, Encoding encoding)        {            if (contents == null)                throw new ArgumentNullException("contents");            using (var stream = this.AppendText(path, encoding))            {                foreach (var line in contents)                {                    stream.WriteLine(line);                }            }        }        /// <summary>        ///  Opens a file, appends the specified string to the file, and then closes the file.         ///  If the file does not exist, this method creates a file, writes the specified string to the file, then closes the file.        /// </summary>        /// <param name="path">The file to append the specified string to.</param>        /// <param name="contents">The string to append to the file.</param>        /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>. <para>-or-</para> <paramref name="contents"/> is <b>null</b>.</exception>        public void AppendAllText(string path, string contents)        {            using (var stream = this.AppendText(path))            {                stream.Write(contents);            }        }        /// <summary>        /// Opens a file, appends the specified string to the file, and then closes the file.        /// If the file does not exist, this method creates a file, writes the specified string to the file, then closes the file.        /// </summary>        /// <param name="path">The file to append the specified string to.</param>        /// <param name="contents">The string to append to the file.</param>        /// <param name="encoding">The character encoding to use.</param>        /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>. <para>-or-</para> <paramref name="contents"/> is <b>null</b>. <para>-or-</para> <paramref name="encoding"/> is <b>null</b>.</exception>        public void AppendAllText(string path, string contents, Encoding encoding)        {            using (var stream = this.AppendText(path, encoding))            {                stream.Write(contents);            }        }        /// <summary>        /// Creates a <see cref="System.IO.StreamWriter"/> that appends UTF-8 encoded text to an existing file.        /// </summary>        /// <param name="path">The path to the file to append to.</param>        /// <returns>A StreamWriter that appends UTF-8 encoded text to an existing file.</returns>        /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>        public StreamWriter AppendText(string path)        {            return this.AppendText(path, Encoding.UTF8);        }        /// <summary>        /// Creates a <see cref="System.IO.StreamWriter"/> that appends UTF-8 encoded text to an existing file.        /// </summary>        /// <param name="path">The path to the file to append to.</param>        /// <param name="encoding">The character encoding to use.</param>        /// <returns>        /// A StreamWriter that appends UTF-8 encoded text to an existing file.        /// </returns>        /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>. <para>-or-</para> <paramref name="encoding"/> is <b>null</b>.</exception>        public StreamWriter AppendText(string path, Encoding encoding)        {            if (encoding == null)                throw new ArgumentNullException("encoding");            return new StreamWriter(new SftpFileStream(this._sftpSession, path, FileMode.Append, FileAccess.Write), encoding);        }        /// <summary>        /// Creates or overwrites a file in the specified path.        /// </summary>        /// <param name="path">The path and name of the file to create.</param>        /// <returns>A <see cref="SftpFileStream"/> that provides read/write access to the file specified in path</returns>        /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>        public SftpFileStream Create(string path)        {            return new SftpFileStream(this._sftpSession, path, FileMode.Create, FileAccess.ReadWrite);        }        /// <summary>        /// Creates or overwrites the specified file.        /// </summary>        /// <param name="path">The path and name of the file to create.</param>        /// <param name="bufferSize">The number of bytes buffered for reads and writes to the file.</param>        /// <returns>A <see cref="SftpFileStream"/> that provides read/write access to the file specified in path</returns>        /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>        public SftpFileStream Create(string path, int bufferSize)        {            return new SftpFileStream(this._sftpSession, path, FileMode.Create, FileAccess.ReadWrite, bufferSize);        }        /// <summary>        /// Creates or opens a file for writing UTF-8 encoded text.        /// </summary>        /// <param name="path">The file to be opened for writing.</param>        /// <returns>A <see cref="System.IO.StreamWriter"/> that writes to the specified file using UTF-8 encoding.</returns>        /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>        public StreamWriter CreateText(string path)        {            return new StreamWriter(this.OpenWrite(path), Encoding.UTF8);        }        /// <summary>        /// Creates or opens a file for writing UTF-8 encoded text.        /// </summary>        /// <param name="path">The file to be opened for writing.</param>        /// <param name="encoding">The character encoding to use.</param>        /// <returns> A <see cref="System.IO.StreamWriter"/> that writes to the specified file using UTF-8 encoding. </returns>        /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>        public StreamWriter CreateText(string path, Encoding encoding)        {            return new StreamWriter(this.OpenWrite(path), encoding);        }        /// <summary>        /// Deletes the specified file or directory. An exception is not thrown if the specified file does not exist.        /// </summary>        /// <param name="path">The name of the file or directory to be deleted. Wildcard characters are not supported.</param>        /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>        /// <exception cref="SshConnectionException">Client is not connected.</exception>        public void Delete(string path)        {            var file = this.Get(path);            file.Delete();        }        /// <summary>        /// Returns the date and time the specified file or directory was last accessed.        /// </summary>        /// <param name="path">The file or directory for which to obtain access date and time information.</param>        /// <returns>A <see cref="System.DateTime"/> structure set to the date and time that the specified file or directory was last accessed. This value is expressed in local time.</returns>        /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>        /// <exception cref="SshConnectionException">Client is not connected.</exception>        public DateTime GetLastAccessTime(string path)        {            var file = this.Get(path);            return file.LastAccessTime;        }        /// <summary>        /// Returns the date and time, in coordinated universal time (UTC), that the specified file or directory was last accessed.        /// </summary>        /// <param name="path">The file or directory for which to obtain access date and time information.</param>        /// <returns>A <see cref="System.DateTime"/> structure set to the date and time that the specified file or directory was last accessed. This value is expressed in UTC time.</returns>        /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>        /// <exception cref="SshConnectionException">Client is not connected.</exception>        public DateTime GetLastAccessTimeUtc(string path)        {            var file = this.Get(path);            return file.LastAccessTime.ToUniversalTime();        }        /// <summary>        /// Returns the date and time the specified file or directory was last written to.        /// </summary>        /// <param name="path">The file or directory for which to obtain write date and time information.</param>        /// <returns>A <see cref="System.DateTime"/> structure set to the date and time that the specified file or directory was last written to. This value is expressed in local time.</returns>        /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>        /// <exception cref="SshConnectionException">Client is not connected.</exception>        public DateTime GetLastWriteTime(string path)        {            var file = this.Get(path);            return file.LastWriteTime;        }        /// <summary>        /// Returns the date and time, in coordinated universal time (UTC), that the specified file or directory was last written to.        /// </summary>        /// <param name="path">The file or directory for which to obtain write date and time information.</param>        /// <returns>A <see cref="System.DateTime"/> structure set to the date and time that the specified file or directory was last written to. This value is expressed in UTC time.</returns>        /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>        /// <exception cref="SshConnectionException">Client is not connected.</exception>        public DateTime GetLastWriteTimeUtc(string path)        {            var file = this.Get(path);            return file.LastWriteTime.ToUniversalTime();        }        /// <summary>        /// Opens a <see cref="SftpFileStream"/> on the specified path with read/write access.        /// </summary>        /// <param name="path">The file to open.</param>        /// <param name="mode">A <see cref="System.IO.FileMode"/> value that specifies whether a file is created if one does not exist, and determines whether the contents of existing files are retained or overwritten.</param>        /// <returns>An unshared <see cref="SftpFileStream"/> that provides access to the specified file, with the specified mode and access.</returns>        /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>        public SftpFileStream Open(string path, FileMode mode)        {            return new SftpFileStream(this._sftpSession, path, mode, FileAccess.ReadWrite);        }        /// <summary>        /// Opens a <see cref="SftpFileStream"/> on the specified path, with the specified mode and access.        /// </summary>        /// <param name="path">The file to open.</param>        /// <param name="mode">A <see cref="System.IO.FileMode"/> value that specifies whether a file is created if one does not exist, and determines whether the contents of existing files are retained or overwritten.</param>        /// <param name="access">A <see cref="System.IO.FileAccess"/> value that specifies the operations that can be performed on the file.</param>        /// <returns>An unshared <see cref="SftpFileStream"/> that provides access to the specified file, with the specified mode and access.</returns>        /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>        public SftpFileStream Open(string path, FileMode mode, FileAccess access)        {            return new SftpFileStream(this._sftpSession, path, mode, access);        }        /// <summary>        /// Opens an existing file for reading.        /// </summary>        /// <param name="path">The file to be opened for reading.</param>        /// <returns>A read-only System.IO.FileStream on the specified path.</returns>        /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>        public SftpFileStream OpenRead(string path)        {            return new SftpFileStream(this._sftpSession, path, FileMode.Open, FileAccess.Read);        }        /// <summary>        /// Opens an existing UTF-8 encoded text file for reading.        /// </summary>        /// <param name="path">The file to be opened for reading.</param>        /// <returns>A <see cref="System.IO.StreamReader"/> on the specified path.</returns>        /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>        public StreamReader OpenText(string path)        {            return new StreamReader(this.OpenRead(path), Encoding.UTF8);        }        /// <summary>        /// Opens an existing file for writing.        /// </summary>        /// <param name="path">The file to be opened for writing.</param>        /// <returns>An unshared <see cref="SftpFileStream"/> object on the specified path with <see cref="System.IO.FileAccess.Write"/> access.</returns>        /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>        public SftpFileStream OpenWrite(string path)        {            return new SftpFileStream(this._sftpSession, path, FileMode.OpenOrCreate, FileAccess.Write);        }        /// <summary>        /// Opens a binary file, reads the contents of the file into a byte array, and then closes the file.        /// </summary>        /// <param name="path">The file to open for reading.</param>        /// <returns>A byte array containing the contents of the file.</returns>        /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>        public byte[] ReadAllBytes(string path)        {            using (var stream = this.OpenRead(path))            {                var buffer = new byte[stream.Length];                stream.Read(buffer, 0, buffer.Length);                return buffer;            }        }        /// <summary>        /// Opens a text file, reads all lines of the file, and then closes the file.        /// </summary>        /// <param name="path">The file to open for reading.</param>        /// <returns>A string array containing all lines of the file.</returns>        /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>        public string[] ReadAllLines(string path)        {            return this.ReadAllLines(path, Encoding.UTF8);        }        /// <summary>        /// Opens a file, reads all lines of the file with the specified encoding, and then closes the file.        /// </summary>        /// <param name="path">The file to open for reading.</param>        /// <param name="encoding">The encoding applied to the contents of the file.</param>        /// <returns>A string array containing all lines of the file.</returns>        /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>        public string[] ReadAllLines(string path, Encoding encoding)        {            var lines = new List<string>();            using (var stream = new StreamReader(this.OpenRead(path), encoding))            {                while (!stream.EndOfStream)                {                    lines.Add(stream.ReadLine());                }            }            return lines.ToArray();        }        /// <summary>        /// Opens a text file, reads all lines of the file, and then closes the file.        /// </summary>        /// <param name="path">The file to open for reading.</param>        /// <returns>A string containing all lines of the file.</returns>        /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>        public string ReadAllText(string path)        {            return this.ReadAllText(path, Encoding.UTF8);        }        /// <summary>        /// Opens a file, reads all lines of the file with the specified encoding, and then closes the file.        /// </summary>        /// <param name="path">The file to open for reading.</param>        /// <param name="encoding">The encoding applied to the contents of the file.</param>        /// <returns>A string containing all lines of the file.</returns>        /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>        public string ReadAllText(string path, Encoding encoding)        {            var lines = new List<string>();            using (var stream = new StreamReader(this.OpenRead(path), encoding))            {                return stream.ReadToEnd();            }        }        /// <summary>        /// Reads the lines of a file.        /// </summary>        /// <param name="path">The file to read.</param>        /// <returns>The lines of the file.</returns>        /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>        public IEnumerable<string> ReadLines(string path)        {            return this.ReadAllLines(path);        }        /// <summary>        /// Read the lines of a file that has a specified encoding.        /// </summary>        /// <param name="path">The file to read.</param>        /// <param name="encoding">The encoding that is applied to the contents of the file.</param>        /// <returns>The lines of the file.</returns>        /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>        public IEnumerable<string> ReadLines(string path, Encoding encoding)        {            return this.ReadAllLines(path, encoding);        }        /// <summary>        /// Sets the date and time the specified file was last accessed.        /// </summary>        /// <param name="path">The file for which to set the access date and time information.</param>        /// <param name="lastAccessTime">A <see cref="System.DateTime"/> containing the value to set for the last access date and time of path. This value is expressed in local time.</param>        [Obsolete("Note: This method currently throws NotImplementedException because it has not yet been implemented.")]        public void SetLastAccessTime(string path, DateTime lastAccessTime)        {            throw new NotImplementedException();        }        /// <summary>        /// Sets the date and time, in coordinated universal time (UTC), that the specified file was last accessed.        /// </summary>        /// <param name="path">The file for which to set the access date and time information.</param>        /// <param name="lastAccessTimeUtc">A <see cref="System.DateTime"/> containing the value to set for the last access date and time of path. This value is expressed in UTC time.</param>        [Obsolete("Note: This method currently throws NotImplementedException because it has not yet been implemented.")]        public void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc)        {            throw new NotImplementedException();        }        /// <summary>        /// Sets the date and time that the specified file was last written to.        /// </summary>        /// <param name="path">The file for which to set the date and time information.</param>        /// <param name="lastWriteTime">A System.DateTime containing the value to set for the last write date and time of path. This value is expressed in local time.</param>        [Obsolete("Note: This method currently throws NotImplementedException because it has not yet been implemented.")]        public void SetLastWriteTime(string path, DateTime lastWriteTime)        {            throw new NotImplementedException();        }        /// <summary>        /// Sets the date and time, in coordinated universal time (UTC), that the specified file was last written to.        /// </summary>        /// <param name="path">The file for which to set the date and time information.</param>        /// <param name="lastWriteTimeUtc">A System.DateTime containing the value to set for the last write date and time of path. This value is expressed in UTC time.</param>        [Obsolete("Note: This method currently throws NotImplementedException because it has not yet been implemented.")]        public void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc)        {            throw new NotImplementedException();        }        /// <summary>        /// Creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten.        /// </summary>        /// <param name="path">The file to write to.</param>        /// <param name="bytes">The bytes to write to the file.</param>        /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>        public void WriteAllBytes(string path, byte[] bytes)        {            using (var stream = this.OpenWrite(path))            {                stream.Write(bytes, 0, bytes.Length);            }        }        /// <summary>        /// Creates a new file, writes a collection of strings to the file, and then closes the file.        /// </summary>        /// <param name="path">The file to write to.</param>        /// <param name="contents">The lines to write to the file.</param>        /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>        public void WriteAllLines(string path, IEnumerable<string> contents)        {            this.WriteAllLines(path, contents, Encoding.UTF8);        }        /// <summary>        /// Creates a new file, write the specified string array to the file, and then closes the file.        /// </summary>        /// <param name="path">The file to write to.</param>        /// <param name="contents">The string array to write to the file.</param>        /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>        public void WriteAllLines(string path, string[] contents)        {            this.WriteAllLines(path, contents, Encoding.UTF8);        }        /// <summary>        /// Creates a new file by using the specified encoding, writes a collection of strings to the file, and then closes the file.        /// </summary>        /// <param name="path">The file to write to.</param>        /// <param name="contents">The lines to write to the file.</param>        /// <param name="encoding">The character encoding to use.</param>        /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>        public void WriteAllLines(string path, IEnumerable<string> contents, Encoding encoding)        {            using (var stream = this.CreateText(path, encoding))            {                foreach (var line in contents)                {                    stream.WriteLine(line);                }            }        }        /// <summary>        /// Creates a new file, writes the specified string array to the file by using the specified encoding, and then closes the file.        /// </summary>        /// <param name="path">The file to write to.</param>        /// <param name="contents">The string array to write to the file.</param>        /// <param name="encoding">An <see cref="System.Text.Encoding"/> object that represents the character encoding applied to the string array.</param>        /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>        public void WriteAllLines(string path, string[] contents, Encoding encoding)        {            using (var stream = this.CreateText(path, encoding))            {                foreach (var line in contents)                {                    stream.WriteLine(line);                }            }        }        /// <summary>        /// Creates a new file, writes the specified string to the file, and then closes the file. If the target file already exists, it is overwritten.        /// </summary>        /// <param name="path">The file to write to.</param>        /// <param name="contents">The string to write to the file.</param>        /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>        public void WriteAllText(string path, string contents)        {            using (var stream = this.CreateText(path))            {                stream.Write(contents);            }        }        /// <summary>        /// Creates a new file, writes the specified string to the file using the specified encoding, and then closes the file. If the target file already exists, it is overwritten.        /// </summary>        /// <param name="path">The file to write to.</param>        /// <param name="contents">The string to write to the file.</param>        /// <param name="encoding">The encoding to apply to the string.</param>        /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>        public void WriteAllText(string path, string contents, Encoding encoding)        {            using (var stream = this.CreateText(path, encoding))            {                stream.Write(contents);            }        }        /// <summary>        /// Gets the <see cref="SftpFileAttributes"/> of the file on the path.        /// </summary>        /// <param name="path">The path to the file.</param>        /// <returns>The <see cref="SftpFileAttributes"/> of the file on the path.</returns>        /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>        public SftpFileAttributes GetAttributes(string path)        {            var fullPath = this._sftpSession.GetCanonicalPath(path);            return this._sftpSession.RequestLStat(fullPath);        }        /// <summary>        /// Sets the specified <see cref="SftpFileAttributes"/> of the file on the specified path.        /// </summary>        /// <param name="path">The path to the file.</param>        /// <param name="fileAttributes">The desired <see cref="SftpFileAttributes"/>.</param>        /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>        public void SetAttributes(string path, SftpFileAttributes fileAttributes)        {            var fullPath = this._sftpSession.GetCanonicalPath(path);            this._sftpSession.RequestSetStat(fullPath, fileAttributes);        }        // Please don't forget this when you implement these methods: <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception>        //public FileSecurity GetAccessControl(string path);        //public FileSecurity GetAccessControl(string path, AccessControlSections includeSections);        //public DateTime GetCreationTime(string path);        //public DateTime GetCreationTimeUtc(string path);        //public void SetAccessControl(string path, FileSecurity fileSecurity);        //public void SetCreationTime(string path, DateTime creationTime);        //public void SetCreationTimeUtc(string path, DateTime creationTimeUtc);        #endregion        /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>        /// <exception cref="SshConnectionException">Client not connected.</exception>        private IEnumerable<SftpFile> InternalListDirectory(string path, SftpListDirectoryAsyncResult asynchResult)        {            if (path == null)                throw new ArgumentNullException("path");            //  Ensure that connection is established.            this.EnsureConnection();            var fullPath = this._sftpSession.GetCanonicalPath(path);            var handle = this._sftpSession.RequestOpenDir(fullPath);            var basePath = fullPath;            if (!basePath.EndsWith("/"))                basePath = string.Format("{0}/", fullPath);            var result = new List<SftpFile>();            var files = this._sftpSession.RequestReadDir(handle);            while (files != null)            {                result.AddRange(from f in files                                select new SftpFile(this._sftpSession, string.Format(CultureInfo.InvariantCulture, "{0}{1}", basePath, f.Key), f.Value));                if (asynchResult != null)                {                    asynchResult.Update(result.Count);                }                files = this._sftpSession.RequestReadDir(handle);            }            this._sftpSession.RequestClose(handle);            return result;        }        /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b> or contains whitespace.</exception>        /// <exception cref="ArgumentException"><paramref name="output"/> is <b>null</b>.</exception>        /// <exception cref="SshConnectionException">Client not connected.</exception>        private void InternalDownloadFile(string path, Stream output, SftpDownloadAsyncResult asynchResult)        {            if (output == null)                throw new ArgumentNullException("output");            if (path.IsNullOrWhiteSpace())                throw new ArgumentException("path");            //  Ensure that connection is established.            this.EnsureConnection();            var fullPath = this._sftpSession.GetCanonicalPath(path);            var handle = this._sftpSession.RequestOpen(fullPath, Flags.Read);            ulong offset = 0;            var data = this._sftpSession.RequestRead(handle, offset, this.BufferSize);            //  Read data while available            while (data.Length > 0)            {                output.Write(data, 0, data.Length);                output.Flush();                offset += (ulong)data.Length;                //  Call callback to report number of bytes read                if (asynchResult != null)                {                    asynchResult.Update(offset);                }                data = this._sftpSession.RequestRead(handle, offset, this.BufferSize);            }            this._sftpSession.RequestClose(handle);        }        /// <exception cref="ArgumentNullException"><paramref name="input"/> is <b>null</b>.</exception>        /// <exception cref="ArgumentException"><paramref name="path"/> is <b>null</b> or contains whitespace.</exception>        /// <exception cref="SshConnectionException">Client not connected.</exception>        private void InternalUploadFile(Stream input, string path, SftpUploadAsyncResult asynchResult, Flags flags)        {            if (input == null)                throw new ArgumentNullException("input");            if (path.IsNullOrWhiteSpace())                throw new ArgumentException("path");            //  Ensure that connection is established.            this.EnsureConnection();            var fullPath = this._sftpSession.GetCanonicalPath(path);            var handle = this._sftpSession.RequestOpen(fullPath, flags);            ulong offset = 0;            var buffer = new byte[this.BufferSize];            var uploadCompleted = false;            do            {                var bytesRead = input.Read(buffer, 0, buffer.Length);                if (bytesRead < this.BufferSize)                {                    var data = new byte[bytesRead];                    Buffer.BlockCopy(buffer, 0, data, 0, bytesRead);                    using (var wait = new AutoResetEvent(false))                    {                        this._sftpSession.RequestWrite(handle, offset, data, wait);                    }                    uploadCompleted = true;                }                else                {                    this._sftpSession.RequestWrite(handle, offset, buffer, null);                }                offset += (uint)bytesRead;                //  Call callback to report number of bytes read                if (asynchResult != null)                {                    asynchResult.Update(offset);                }            } while (!uploadCompleted);            this._sftpSession.RequestClose(handle);        }        partial void ExecuteThread(Action action);        /// <summary>        /// Called when client is connected to the server.        /// </summary>        protected override void OnConnected()        {            base.OnConnected();            this._sftpSession = new SftpSession(this.Session, this.OperationTimeout);            this._sftpSession.Connect();            //  Resolve current running version            this.ProtocolVersion = this._sftpSession.ProtocolVersion;        }        /// <summary>        /// Called when client is disconnecting from the server.        /// </summary>        protected override void OnDisconnecting()        {            base.OnDisconnecting();            this._sftpSession.Disconnect();        }        /// <summary>        /// Releases unmanaged and - optionally - managed resources        /// </summary>        /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged ResourceMessages.</param>        protected override void Dispose(bool disposing)        {            if (this._sftpSession != null)            {                this._sftpSession.Dispose();                this._sftpSession = null;            }            if (this._disposeConnectionInfo)                ((IDisposable)this.ConnectionInfo).Dispose();            base.Dispose(disposing);        }    }}
 |