| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153 |
- 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;
- using System.Net;
- using Renci.SshNet.Abstractions;
- namespace Renci.SshNet
- {
- /// <summary>
- /// Implementation of the SSH File Transfer Protocol (SFTP) over SSH.
- /// </summary>
- public class SftpClient : BaseClient
- {
- /// <summary>
- /// Holds the <see cref="ISftpSession"/> instance that is used to communicate to the
- /// SFTP server.
- /// </summary>
- private ISftpSession _sftpSession;
- /// <summary>
- /// Holds the operation timeout.
- /// </summary>
- private TimeSpan _operationTimeout;
- /// <summary>
- /// Holds the size of the buffer.
- /// </summary>
- private uint _bufferSize;
- /// <summary>
- /// Gets or sets the operation timeout.
- /// </summary>
- /// <value>
- /// The timeout to wait until an operation completes. The default value is negative
- /// one (-1) milliseconds, which indicates an infinite timeout period.
- /// </value>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- public TimeSpan OperationTimeout
- {
- get
- {
- CheckDisposed();
- return _operationTimeout;
- }
- set
- {
- CheckDisposed();
- _operationTimeout = value;
- }
- }
- /// <summary>
- /// Gets or sets the maximum size of the buffer in bytes.
- /// </summary>
- /// <value>
- /// The size of the buffer. The default buffer size is 32768 bytes (32 KB).
- /// </value>
- /// <remarks>
- /// <para>
- /// For write operations, this limits the size of the payload for
- /// individual SSH_FXP_WRITE messages. The actual size is always
- /// capped at the maximum packet size supported by the peer
- /// (minus the size of protocol fields).
- /// </para>
- /// <para>
- /// For read operations, this controls the size of the payload which
- /// is requested from the peer in each SSH_FXP_READ message. The peer
- /// will send the requested number of bytes in one or more SSH_FXP_DATA
- /// messages. To optimize the size of the SSH packets sent by the peer,
- /// the actual requested size will take into account the size of the
- /// SSH_FXP_DATA protocol fields.
- /// </para>
- /// <para>
- /// The size of the each indivual SSH_FXP_DATA message is limited to the
- /// local maximum packet size of the channel, which is set to <c>64 KB</c>
- /// for SSH.NET. However, the peer can limit this even further.
- /// </para>
- /// </remarks>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- public uint BufferSize
- {
- get
- {
- CheckDisposed();
- return _bufferSize;
- }
- set
- {
- CheckDisposed();
- _bufferSize = value;
- }
- }
- /// <summary>
- /// Gets remote working directory.
- /// </summary>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- public string WorkingDirectory
- {
- get
- {
- CheckDisposed();
- if (_sftpSession == null)
- throw new SshConnectionException("Client not connected.");
- return _sftpSession.WorkingDirectory;
- }
- }
- /// <summary>
- /// Gets sftp protocol version.
- /// </summary>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- public int ProtocolVersion
- {
- get
- {
- CheckDisposed();
- if (_sftpSession == null)
- throw new SshConnectionException("Client not connected.");
- return (int) _sftpSession.ProtocolVersion;
- }
- }
- #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)
- : this(connectionInfo, false)
- {
- }
- /// <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 only whitespace characters.</exception>
- /// <exception cref="ArgumentOutOfRangeException"><paramref name="port"/> is not within <see cref="IPEndPoint.MinPort"/> and <see cref="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), 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 only whitespace characters.</exception>
- public SftpClient(string host, string username, string password)
- : this(host, ConnectionInfo.DefaultPort, 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 only whitespace characters.</exception>
- /// <exception cref="ArgumentOutOfRangeException"><paramref name="port"/> is not within <see cref="IPEndPoint.MinPort"/> and <see cref="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), 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 only whitespace characters.</exception>
- public SftpClient(string host, string username, params PrivateKeyFile[] keyFiles)
- : this(host, ConnectionInfo.DefaultPort, username, keyFiles)
- {
- }
- /// <summary>
- /// Initializes a new instance of the <see cref="SftpClient"/> class.
- /// </summary>
- /// <param name="connectionInfo">The connection info.</param>
- /// <param name="ownsConnectionInfo">Specified whether this instance owns the connection info.</param>
- /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is <c>null</c>.</exception>
- /// <remarks>
- /// If <paramref name="ownsConnectionInfo"/> is <c>true</c>, the connection info will be disposed when this
- /// instance is disposed.
- /// </remarks>
- private SftpClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo)
- : this(connectionInfo, ownsConnectionInfo, new ServiceFactory())
- {
- }
- /// <summary>
- /// Initializes a new instance of the <see cref="SftpClient"/> class.
- /// </summary>
- /// <param name="connectionInfo">The connection info.</param>
- /// <param name="ownsConnectionInfo">Specified whether this instance owns the connection info.</param>
- /// <param name="serviceFactory">The factory to use for creating new services.</param>
- /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is <c>null</c>.</exception>
- /// <exception cref="ArgumentNullException"><paramref name="serviceFactory"/> is <c>null</c>.</exception>
- /// <remarks>
- /// If <paramref name="ownsConnectionInfo"/> is <c>true</c>, the connection info will be disposed when this
- /// instance is disposed.
- /// </remarks>
- internal SftpClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo, IServiceFactory serviceFactory)
- : base(connectionInfo, ownsConnectionInfo, serviceFactory)
- {
- OperationTimeout = SshNet.Session.InfiniteTimeSpan;
- BufferSize = 1024 * 32;
- }
- #endregion Constructors
- /// <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"><paramref name="path"/> was not found on the remote host.</exception>
- /// <exception cref="SshException">A SSH error where <see cref="P:System.Exception.Message"/> is the message from the remote host.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- public void ChangeDirectory(string path)
- {
- CheckDisposed();
- if (path == null)
- throw new ArgumentNullException("path");
- if (_sftpSession == null)
- throw new SshConnectionException("Client not connected.");
- _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"><paramref name="path"/> was not found on the remote host.</exception>
- /// <exception cref="SshException">A SSH error where <see cref="P:System.Exception.Message"/> is the message from the remote host.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- public void ChangePermissions(string path, short mode)
- {
- var file = 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 only whitespace characters.</exception>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="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="SshException">A SSH error where <see cref="P:System.Exception.Message"/> is the message from the remote host.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- public void CreateDirectory(string path)
- {
- CheckDisposed();
- if (path.IsNullOrWhiteSpace())
- throw new ArgumentException(path);
- if (_sftpSession == null)
- throw new SshConnectionException("Client not connected.");
- var fullPath = _sftpSession.GetCanonicalPath(path);
- _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 only whitespace characters.</exception>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="SftpPathNotFoundException"><paramref name="path"/> was not found on the remote host.</exception>
- /// <exception cref="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="SshException">A SSH error where <see cref="P:System.Exception.Message"/> is the message from the remote host.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- public void DeleteDirectory(string path)
- {
- CheckDisposed();
- if (path.IsNullOrWhiteSpace())
- throw new ArgumentException("path");
- if (_sftpSession == null)
- throw new SshConnectionException("Client not connected.");
- var fullPath = _sftpSession.GetCanonicalPath(path);
- _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 only whitespace characters.</exception>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="SftpPathNotFoundException"><paramref name="path"/> was not found on the remote host.</exception>
- /// <exception cref="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="SshException">A SSH error where <see cref="P:System.Exception.Message"/> is the message from the remote host.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- public void DeleteFile(string path)
- {
- CheckDisposed();
- if (path.IsNullOrWhiteSpace())
- throw new ArgumentException("path");
- if (_sftpSession == null)
- throw new SshConnectionException("Client not connected.");
- var fullPath = _sftpSession.GetCanonicalPath(path);
- _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="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="SshException">A SSH error where <see cref="P:System.Exception.Message"/> is the message from the remote host.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- public void RenameFile(string oldPath, string newPath)
- {
- RenameFile(oldPath, newPath, false);
- }
- /// <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>
- /// <param name="isPosix">if set to <c>true</c> then perform a posix rename.</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="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="SshException">A SSH error where <see cref="P:System.Exception.Message" /> is the message from the remote host.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- public void RenameFile(string oldPath, string newPath, bool isPosix)
- {
- CheckDisposed();
- if (oldPath == null)
- throw new ArgumentNullException("oldPath");
- if (newPath == null)
- throw new ArgumentNullException("newPath");
- if (_sftpSession == null)
- throw new SshConnectionException("Client not connected.");
- var oldFullPath = _sftpSession.GetCanonicalPath(oldPath);
- var newFullPath = _sftpSession.GetCanonicalPath(newPath);
- if (isPosix)
- {
- _sftpSession.RequestPosixRename(oldFullPath, newFullPath);
- }
- else
- {
- _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 only whitespace characters.</exception>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="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="SshException">A SSH error where <see cref="P:System.Exception.Message"/> is the message from the remote host.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- public void SymbolicLink(string path, string linkPath)
- {
- CheckDisposed();
- if (path.IsNullOrWhiteSpace())
- throw new ArgumentException("path");
- if (linkPath.IsNullOrWhiteSpace())
- throw new ArgumentException("linkPath");
- if (_sftpSession == null)
- throw new SshConnectionException("Client not connected.");
- var fullPath = _sftpSession.GetCanonicalPath(path);
- var linkFullPath = _sftpSession.GetCanonicalPath(linkPath);
- _sftpSession.RequestSymLink(fullPath, linkFullPath);
- }
- /// <summary>
- /// Retrieves list of files in remote directory.
- /// </summary>
- /// <param name="path">The path.</param>
- /// <param name="listCallback">The list callback.</param>
- /// <returns>
- /// A list of files.
- /// </returns>
- /// <exception cref="ArgumentNullException"><paramref name="path" /> is <b>null</b>.</exception>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="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="SshException">A SSH error where <see cref="P:System.Exception.Message" /> is the message from the remote host.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- public IEnumerable<SftpFile> ListDirectory(string path, Action<int> listCallback = null)
- {
- CheckDisposed();
- return InternalListDirectory(path, listCallback);
- }
- /// <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>
- /// <param name="listCallback">The list callback.</param>
- /// <returns>
- /// An <see cref="IAsyncResult" /> that references the asynchronous operation.
- /// </returns>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- public IAsyncResult BeginListDirectory(string path, AsyncCallback asyncCallback, object state, Action<int> listCallback = null)
- {
- CheckDisposed();
- var asyncResult = new SftpListDirectoryAsyncResult(asyncCallback, state);
- ThreadAbstraction.ExecuteThread(() =>
- {
- try
- {
- var result = InternalListDirectory(path, count =>
- {
- asyncResult.Update(count);
- if (listCallback != null)
- {
- listCallback(count);
- }
- });
- 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>
- /// A list of files.
- /// </returns>
- /// <exception cref="ArgumentException">The <see cref="IAsyncResult"/> object did not come from the corresponding async method on this type.<para>-or-</para><see cref="EndListDirectory(IAsyncResult)"/> was called multiple times with the same <see cref="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>
- /// A reference to <see cref="SftpFile"/> file object.
- /// </returns>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="SftpPathNotFoundException"><paramref name="path"/> was not found on the remote host.</exception>
- /// <exception cref="ArgumentNullException"><paramref name="path" /> is <b>null</b>.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- public SftpFile Get(string path)
- {
- CheckDisposed();
- if (path == null)
- throw new ArgumentNullException("path");
- if (_sftpSession == null)
- throw new SshConnectionException("Client not connected.");
- var fullPath = _sftpSession.GetCanonicalPath(path);
- var attributes = _sftpSession.RequestStat(fullPath);
- return new SftpFile(_sftpSession, fullPath, attributes);
- }
- /// <summary>
- /// Checks whether file or 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 only whitespace characters.</exception>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="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="SshException">A SSH error where <see cref="P:System.Exception.Message"/> is the message from the remote host.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- public bool Exists(string path)
- {
- CheckDisposed();
- if (path.IsNullOrWhiteSpace())
- throw new ArgumentException("path");
- if (_sftpSession == null)
- throw new SshConnectionException("Client not connected.");
- var fullPath = _sftpSession.GetCanonicalPath(path);
- // using SSH_FXP_REALPATH is not an alternative the SFTP specification has not always
- // been clear on how the server should respond when the specified path is not present
- // on the server:
- //
- // SSH 1 to 4:
- // No mention of how the server should respond if the path is not present on the server.
- //
- // SSH 5:
- // The server SHOULD fail the request if the path is not present on the server.
- //
- // SSH 6:
- // Draft 06: The server SHOULD fail the request if the path is not present on the server.
- // Draft 07 to 13: The server MUST NOT fail the request if the path does not exist.
- //
- // Note that SSH 6 (draft 06 and forward) allows for more control options, but we
- // currently only support up to v3.
- try
- {
- _sftpSession.RequestLStat(fullPath);
- return true;
- }
- catch (SftpPathNotFoundException)
- {
- return false;
- }
- }
- /// <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>
- /// <param name="downloadCallback">The download callback.</param>
- /// <exception cref="ArgumentNullException"><paramref name="output" /> is <b>null</b>.</exception>
- /// <exception cref="ArgumentException"><paramref name="path" /> is <b>null</b> or contains only whitespace characters.</exception>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="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="SftpPathNotFoundException"><paramref name="path"/> was not found on the remote host.</exception>///
- /// <exception cref="SshException">A SSH error where <see cref="P:System.Exception.Message" /> is the message from the remote host.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</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, Action<ulong> downloadCallback = null)
- {
- CheckDisposed();
- InternalDownloadFile(path, output, null, downloadCallback);
- }
- /// <summary>
- /// Begins an asynchronous file downloading into the stream.
- /// </summary>
- /// <param name="path">The path.</param>
- /// <param name="output">The output.</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 only whitespace characters.</exception>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="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="SshException">A SSH error where <see cref="P:System.Exception.Message" /> is the message from the remote host.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</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)
- {
- return BeginDownloadFile(path, output, null, 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>
- /// <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 only whitespace characters.</exception>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="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="SshException">A SSH error where <see cref="P:System.Exception.Message" /> is the message from the remote host.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</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)
- {
- return BeginDownloadFile(path, output, asyncCallback, 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>
- /// <param name="downloadCallback">The download callback.</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 only whitespace characters.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</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, Action<ulong> downloadCallback = null)
- {
- CheckDisposed();
- if (path.IsNullOrWhiteSpace())
- throw new ArgumentException("path");
- if (output == null)
- throw new ArgumentNullException("output");
- var asyncResult = new SftpDownloadAsyncResult(asyncCallback, state);
- ThreadAbstraction.ExecuteThread(() =>
- {
- try
- {
- InternalDownloadFile(path, output, asyncResult, offset =>
- {
- asyncResult.Update(offset);
- if (downloadCallback != null)
- {
- downloadCallback(offset);
- }
- });
- 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 <see cref="IAsyncResult"/> object did not come from the corresponding async method on this type.<para>-or-</para><see cref="EndDownloadFile(IAsyncResult)"/> was called multiple times with the same <see cref="IAsyncResult"/>.</exception>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="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="SftpPathNotFoundException">The path was not found on the remote host.</exception>
- /// <exception cref="SshException">A SSH error where <see cref="P:System.Exception.Message" /> is the message from the remote host.</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>
- /// <param name="uploadCallback">The upload callback.</param>
- /// <exception cref="ArgumentNullException"><paramref name="input" /> is <b>null</b>.</exception>
- /// <exception cref="ArgumentException"><paramref name="path" /> is <b>null</b> or contains only whitespace characters.</exception>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="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="SshException">A SSH error where <see cref="P:System.Exception.Message" /> is the message from the remote host.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</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, Action<ulong> uploadCallback = null)
- {
- UploadFile(input, path, true, uploadCallback);
- }
- /// <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>
- /// <param name="uploadCallback">The upload callback.</param>
- /// <exception cref="ArgumentNullException"><paramref name="input" /> is <b>null</b>.</exception>
- /// <exception cref="ArgumentException"><paramref name="path" /> is <b>null</b> or contains only whitespace characters.</exception>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="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="SshException">A SSH error where <see cref="P:System.Exception.Message" /> is the message from the remote host.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</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, Action<ulong> uploadCallback = null)
- {
- CheckDisposed();
- var flags = Flags.Write | Flags.Truncate;
- if (canOverride)
- flags |= Flags.CreateNewOrOpen;
- else
- flags |= Flags.CreateNew;
- InternalUploadFile(input, path, flags, null, uploadCallback);
- }
- /// <summary>
- /// Begins an asynchronous uploading the stream into remote file.
- /// </summary>
- /// <param name="input">Data input stream.</param>
- /// <param name="path">Remote file path.</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 only whitespace characters.</exception>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="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="SshException">A SSH error where <see cref="P:System.Exception.Message" /> is the message from the remote host.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- /// <remarks>
- /// <para>
- /// Method calls made by this method to <paramref name="input" />, may under certain conditions result in exceptions thrown by the stream.
- /// </para>
- /// <para>
- /// If the remote file already exists, it is overwritten and truncated.
- /// </para>
- /// </remarks>
- public IAsyncResult BeginUploadFile(Stream input, string path)
- {
- return BeginUploadFile(input, path, true, null, null);
- }
- /// <summary>
- /// Begins an asynchronous uploading the stream 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>
- /// <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 only whitespace characters.</exception>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="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="SshException">A SSH error where <see cref="P:System.Exception.Message" /> is the message from the remote host.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- /// <remarks>
- /// <para>
- /// Method calls made by this method to <paramref name="input" />, may under certain conditions result in exceptions thrown by the stream.
- /// </para>
- /// <para>
- /// If the remote file already exists, it is overwritten and truncated.
- /// </para>
- /// </remarks>
- public IAsyncResult BeginUploadFile(Stream input, string path, AsyncCallback asyncCallback)
- {
- return BeginUploadFile(input, path, true, asyncCallback, null);
- }
- /// <summary>
- /// Begins an asynchronous uploading the stream 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>
- /// <param name="uploadCallback">The upload callback.</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 only whitespace characters.</exception>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="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="SshException">A SSH error where <see cref="P:System.Exception.Message" /> is the message from the remote host.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- /// <remarks>
- /// <para>
- /// Method calls made by this method to <paramref name="input" />, may under certain conditions result in exceptions thrown by the stream.
- /// </para>
- /// <para>
- /// If the remote file already exists, it is overwritten and truncated.
- /// </para>
- /// </remarks>
- public IAsyncResult BeginUploadFile(Stream input, string path, AsyncCallback asyncCallback, object state, Action<ulong> uploadCallback = null)
- {
- return BeginUploadFile(input, path, true, asyncCallback, state, uploadCallback);
- }
- /// <summary>
- /// Begins an asynchronous uploading the stream into remote file.
- /// </summary>
- /// <param name="input">Data input stream.</param>
- /// <param name="path">Remote file path.</param>
- /// <param name="canOverride">Specified whether an existing file can 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>
- /// <param name="uploadCallback">The upload callback.</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 only whitespace characters.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- /// <remarks>
- /// <para>
- /// Method calls made by this method to <paramref name="input" />, may under certain conditions result in exceptions thrown by the stream.
- /// </para>
- /// <para>
- /// When <paramref name="path"/> refers to an existing file, set <paramref name="canOverride"/> to <c>true</c> to overwrite and truncate that file.
- /// If <paramref name="canOverride"/> is <c>false</c>, the upload will fail and <see cref="EndUploadFile(IAsyncResult)"/> will throw an
- /// <see cref="SshException"/>.
- /// </para>
- /// </remarks>
- public IAsyncResult BeginUploadFile(Stream input, string path, bool canOverride, AsyncCallback asyncCallback, object state, Action<ulong> uploadCallback = null)
- {
- CheckDisposed();
- 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;
- var asyncResult = new SftpUploadAsyncResult(asyncCallback, state);
- ThreadAbstraction.ExecuteThread(() =>
- {
- try
- {
- InternalUploadFile(input, path, flags, asyncResult, offset =>
- {
- asyncResult.Update(offset);
- if (uploadCallback != null)
- {
- uploadCallback(offset);
- }
- });
- asyncResult.SetAsCompleted(null, false);
- }
- catch (Exception exp)
- {
- asyncResult.SetAsCompleted(exp, false);
- }
- });
- return asyncResult;
- }
- /// <summary>
- /// Ends an asynchronous uploading the stream into remote file.
- /// </summary>
- /// <param name="asyncResult">The pending asynchronous SFTP request.</param>
- /// <exception cref="ArgumentException">The <see cref="IAsyncResult"/> object did not come from the corresponding async method on this type.<para>-or-</para><see cref="EndUploadFile(IAsyncResult)"/> was called multiple times with the same <see cref="IAsyncResult"/>.</exception>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="SftpPathNotFoundException">The directory of the file was not found on the remote host.</exception>
- /// <exception cref="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="SshException">A SSH error where <see cref="P:System.Exception.Message" /> is the message from the remote host.</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();
- }
- /// <summary>
- /// Gets status using statvfs@openssh.com request.
- /// </summary>
- /// <param name="path">The path.</param>
- /// <returns>
- /// A <see cref="SftpFileSytemInformation"/> instance that contains file status information.
- /// </returns>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="ArgumentNullException"><paramref name="path" /> is <b>null</b>.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- public SftpFileSytemInformation GetStatus(string path)
- {
- CheckDisposed();
- if (path == null)
- throw new ArgumentNullException("path");
- if (_sftpSession == null)
- throw new SshConnectionException("Client not connected.");
- var fullPath = _sftpSession.GetCanonicalPath(path);
- return _sftpSession.RequestStatVfs(fullPath);
- }
- #region File Methods
- /// <summary>
- /// Appends lines to a file, and 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>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="SftpPathNotFoundException"><paramref name="path"/> was not found on the remote host.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- public void AppendAllLines(string path, IEnumerable<string> contents)
- {
- CheckDisposed();
- if (contents == null)
- throw new ArgumentNullException("contents");
- using (var stream = AppendText(path))
- {
- foreach (var line in contents)
- {
- stream.WriteLine(line);
- }
- }
- }
- /// <summary>
- /// Appends lines to a file by using a specified encoding, and 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>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="SftpPathNotFoundException"><paramref name="path"/> was not found on the remote host.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- public void AppendAllLines(string path, IEnumerable<string> contents, Encoding encoding)
- {
- CheckDisposed();
- if (contents == null)
- throw new ArgumentNullException("contents");
- using (var stream = AppendText(path, encoding))
- {
- foreach (var line in contents)
- {
- stream.WriteLine(line);
- }
- }
- }
- /// <summary>
- /// Appends the specified string to the file, and 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>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="SftpPathNotFoundException"><paramref name="path"/> was not found on the remote host.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- public void AppendAllText(string path, string contents)
- {
- using (var stream = AppendText(path))
- {
- stream.Write(contents);
- }
- }
- /// <summary>
- /// Appends the specified string to the file, and 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>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="SftpPathNotFoundException"><paramref name="path"/> was not found on the remote host.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- public void AppendAllText(string path, string contents, Encoding encoding)
- {
- using (var stream = AppendText(path, encoding))
- {
- stream.Write(contents);
- }
- }
- /// <summary>
- /// Creates a <see cref="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 <see cref="StreamWriter"/> that appends UTF-8 encoded text to an existing file.
- /// </returns>
- /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="SftpPathNotFoundException"><paramref name="path"/> was not found on the remote host.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- public StreamWriter AppendText(string path)
- {
- return AppendText(path, Encoding.UTF8);
- }
- /// <summary>
- /// Creates a <see cref="StreamWriter"/> that appends text to an existing file using the specified encoding.
- /// </summary>
- /// <param name="path">The path to the file to append to.</param>
- /// <param name="encoding">The character encoding to use.</param>
- /// <returns>
- /// A <see cref="StreamWriter"/> that appends text to an existing file using the specified encoding.
- /// </returns>
- /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>. <para>-or-</para> <paramref name="encoding"/> is <b>null</b>.</exception>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="SftpPathNotFoundException"><paramref name="path"/> was not found on the remote host.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- public StreamWriter AppendText(string path, Encoding encoding)
- {
- CheckDisposed();
- if (encoding == null)
- throw new ArgumentNullException("encoding");
- return new StreamWriter(new SftpFileStream(_sftpSession, path, FileMode.Append, FileAccess.Write, (int) _bufferSize), 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>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- /// <remarks>
- /// If the target file already exists, it is first truncated to zero bytes.
- /// </remarks>
- public SftpFileStream Create(string path)
- {
- CheckDisposed();
- return new SftpFileStream(_sftpSession, path, FileMode.Create, FileAccess.ReadWrite, (int) _bufferSize);
- }
- /// <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 maximum 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>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- /// <remarks>
- /// If the target file already exists, it is first truncated to zero bytes.
- /// </remarks>
- public SftpFileStream Create(string path, int bufferSize)
- {
- CheckDisposed();
- return new SftpFileStream(_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="StreamWriter"/> that writes to the specified file using UTF-8 encoding.
- /// </returns>
- /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- /// <remarks>
- /// <para>
- /// If the target file already exists, it is overwritten. It is not first truncated to zero bytes.
- /// </para>
- /// <para>
- /// If the target file does not exist, it is created.
- /// </para>
- /// </remarks>
- public StreamWriter CreateText(string path)
- {
- return CreateText(path, Encoding.UTF8);
- }
- /// <summary>
- /// Creates or opens a file for writing text using the specified encoding.
- /// </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="StreamWriter"/> that writes to the specified file using the specified encoding.
- /// </returns>
- /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- /// <remarks>
- /// <para>
- /// If the target file already exists, it is overwritten. It is not first truncated to zero bytes.
- /// </para>
- /// <para>
- /// If the target file does not exist, it is created.
- /// </para>
- /// </remarks>
- public StreamWriter CreateText(string path, Encoding encoding)
- {
- CheckDisposed();
- return new StreamWriter(OpenWrite(path), encoding);
- }
- /// <summary>
- /// Deletes the specified file or directory.
- /// </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>
- /// <exception cref="SftpPathNotFoundException"><paramref name="path"/> was not found on the remote host.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- public void Delete(string path)
- {
- var file = 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="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>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- public DateTime GetLastAccessTime(string path)
- {
- var file = 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="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>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- public DateTime GetLastAccessTimeUtc(string path)
- {
- var lastAccessTime = GetLastAccessTime(path);
- return 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="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>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- public DateTime GetLastWriteTime(string path)
- {
- var file = 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="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>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- public DateTime GetLastWriteTimeUtc(string path)
- {
- var lastWriteTime = GetLastWriteTime(path);
- return 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="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 read/write access.
- /// </returns>
- /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- public SftpFileStream Open(string path, FileMode mode)
- {
- return Open(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="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="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>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- public SftpFileStream Open(string path, FileMode mode, FileAccess access)
- {
- CheckDisposed();
- return new SftpFileStream(_sftpSession, path, mode, access, (int) _bufferSize);
- }
- /// <summary>
- /// Opens an existing file for reading.
- /// </summary>
- /// <param name="path">The file to be opened for reading.</param>
- /// <returns>
- /// A read-only <see cref="SftpFileStream"/> on the specified path.
- /// </returns>
- /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- public SftpFileStream OpenRead(string path)
- {
- return Open(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="StreamReader"/> on the specified path.
- /// </returns>
- /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- public StreamReader OpenText(string path)
- {
- return new StreamReader(OpenRead(path), Encoding.UTF8);
- }
- /// <summary>
- /// Opens a 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="FileAccess.Write"/> access.
- /// </returns>
- /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- /// <remarks>
- /// If the file does not exist, it is created.
- /// </remarks>
- public SftpFileStream OpenWrite(string path)
- {
- CheckDisposed();
- return new SftpFileStream(_sftpSession, path, FileMode.OpenOrCreate, FileAccess.Write,
- (int) _bufferSize);
- }
- /// <summary>
- /// Opens a binary file, reads the contents of the file into a byte array, and 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>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- public byte[] ReadAllBytes(string path)
- {
- using (var stream = 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 using UTF-8 encoding, and 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>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- public string[] ReadAllLines(string path)
- {
- return ReadAllLines(path, Encoding.UTF8);
- }
- /// <summary>
- /// Opens a file, reads all lines of the file with the specified encoding, and 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>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- public string[] ReadAllLines(string path, Encoding encoding)
- {
- var lines = new List<string>();
- using (var stream = new StreamReader(OpenRead(path), encoding))
- {
- while (!stream.EndOfStream)
- {
- lines.Add(stream.ReadLine());
- }
- }
- return lines.ToArray();
- }
- /// <summary>
- /// Opens a text file, reads all lines of the file with the UTF-8 encoding, and 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>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- public string ReadAllText(string path)
- {
- return ReadAllText(path, Encoding.UTF8);
- }
- /// <summary>
- /// Opens a file, reads all lines of the file with the specified encoding, and 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>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- public string ReadAllText(string path, Encoding encoding)
- {
- using (var stream = new StreamReader(OpenRead(path), encoding))
- {
- return stream.ReadToEnd();
- }
- }
- /// <summary>
- /// Reads the lines of a file with the UTF-8 encoding.
- /// </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>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- public IEnumerable<string> ReadLines(string path)
- {
- return 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>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- public IEnumerable<string> ReadLines(string path, Encoding encoding)
- {
- return 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="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>
- /// Writes the specified byte array to the specified file, and closes the file.
- /// </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>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- /// <remarks>
- /// <para>
- /// If the target file already exists, it is overwritten. It is not first truncated to zero bytes.
- /// </para>
- /// <para>
- /// If the target file does not exist, it is created.
- /// </para>
- /// </remarks>
- public void WriteAllBytes(string path, byte[] bytes)
- {
- using (var stream = OpenWrite(path))
- {
- stream.Write(bytes, 0, bytes.Length);
- }
- }
- /// <summary>
- /// Writes a collection of strings to the file using the UTF-8 encoding, and 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>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- /// <remarks>
- /// <para>
- /// If the target file already exists, it is overwritten. It is not first truncated to zero bytes.
- /// </para>
- /// <para>
- /// If the target file does not exist, it is created.
- /// </para>
- /// </remarks>
- public void WriteAllLines(string path, IEnumerable<string> contents)
- {
- WriteAllLines(path, contents, Encoding.UTF8);
- }
- /// <summary>
- /// Write the specified string array to the file using the UTF-8 encoding, and 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>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- /// <remarks>
- /// <para>
- /// If the target file already exists, it is overwritten. It is not first truncated to zero bytes.
- /// </para>
- /// <para>
- /// If the target file does not exist, it is created.
- /// </para>
- /// </remarks>
- public void WriteAllLines(string path, string[] contents)
- {
- WriteAllLines(path, contents, Encoding.UTF8);
- }
- /// <summary>
- /// Writes a collection of strings to the file using the specified encoding, and 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>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- /// <remarks>
- /// <para>
- /// If the target file already exists, it is overwritten. It is not first truncated to zero bytes.
- /// </para>
- /// <para>
- /// If the target file does not exist, it is created.
- /// </para>
- /// </remarks>
- public void WriteAllLines(string path, IEnumerable<string> contents, Encoding encoding)
- {
- using (var stream = CreateText(path, encoding))
- {
- foreach (var line in contents)
- {
- stream.WriteLine(line);
- }
- }
- }
- /// <summary>
- /// Writes the specified string array to the file by using the specified encoding, and 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="Encoding"/> object that represents the character encoding applied to the string array.</param>
- /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- /// <remarks>
- /// <para>
- /// If the target file already exists, it is overwritten. It is not first truncated to zero bytes.
- /// </para>
- /// <para>
- /// If the target file does not exist, it is created.
- /// </para>
- /// </remarks>
- public void WriteAllLines(string path, string[] contents, Encoding encoding)
- {
- using (var stream = CreateText(path, encoding))
- {
- foreach (var line in contents)
- {
- stream.WriteLine(line);
- }
- }
- }
- /// <summary>
- /// Writes the specified string to the file using the UTF-8 encoding, and closes the file.
- /// </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>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- /// <para>
- /// If the target file already exists, it is overwritten. It is not first truncated to zero bytes.
- /// </para>
- /// <remarks>
- /// <para>
- /// If the target file already exists, it is overwritten. It is not first truncated to zero bytes.
- /// </para>
- /// <para>
- /// If the target file does not exist, it is created.
- /// </para>
- /// </remarks>
- public void WriteAllText(string path, string contents)
- {
- using (var stream = CreateText(path))
- {
- stream.Write(contents);
- }
- }
- /// <summary>
- /// Writes the specified string to the file using the specified encoding, and closes the file.
- /// </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>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- /// <remarks>
- /// <para>
- /// If the target file already exists, it is overwritten. It is not first truncated to zero bytes.
- /// </para>
- /// <para>
- /// If the target file does not exist, it is created.
- /// </para>
- /// </remarks>
- public void WriteAllText(string path, string contents, Encoding encoding)
- {
- using (var stream = 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>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="SftpPathNotFoundException"><paramref name="path"/> was not found on the remote host.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- public SftpFileAttributes GetAttributes(string path)
- {
- CheckDisposed();
- if (_sftpSession == null)
- throw new SshConnectionException("Client not connected.");
- var fullPath = _sftpSession.GetCanonicalPath(path);
- return _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>
- /// <exception cref="SshConnectionException">Client is not connected.</exception>
- /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
- public void SetAttributes(string path, SftpFileAttributes fileAttributes)
- {
- CheckDisposed();
- if (_sftpSession == null)
- throw new SshConnectionException("Client not connected.");
- var fullPath = _sftpSession.GetCanonicalPath(path);
- _sftpSession.RequestSetStat(fullPath, fileAttributes);
- }
- // Please don't forget this when you implement these methods: <exception cref="ArgumentNullException"><paramref name="path"/> is <c>null</c>.</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 // File Methods
- #region SynchronizeDirectories
- /// <summary>
- /// Synchronizes the directories.
- /// </summary>
- /// <param name="sourcePath">The source path.</param>
- /// <param name="destinationPath">The destination path.</param>
- /// <param name="searchPattern">The search pattern.</param>
- /// <returns>
- /// A list of uploaded files.
- /// </returns>
- /// <exception cref="ArgumentNullException"><paramref name="sourcePath"/> is <c>null</c>.</exception>
- /// <exception cref="ArgumentException"><paramref name="destinationPath"/> is <c>null</c> or contains only whitespace.</exception>
- /// <exception cref="SftpPathNotFoundException"><paramref name="destinationPath"/> was not found on the remote host.</exception>
- public IEnumerable<FileInfo> SynchronizeDirectories(string sourcePath, string destinationPath, string searchPattern)
- {
- if (sourcePath == null)
- throw new ArgumentNullException("sourcePath");
- if (destinationPath.IsNullOrWhiteSpace())
- throw new ArgumentException("destinationPath");
- return InternalSynchronizeDirectories(sourcePath, destinationPath, searchPattern, null);
- }
- /// <summary>
- /// Begins the synchronize directories.
- /// </summary>
- /// <param name="sourcePath">The source path.</param>
- /// <param name="destinationPath">The destination path.</param>
- /// <param name="searchPattern">The search pattern.</param>
- /// <param name="asyncCallback">The async callback.</param>
- /// <param name="state">The state.</param>
- /// <returns>
- /// An <see cref="IAsyncResult" /> that represents the asynchronous directory synchronization.
- /// </returns>
- /// <exception cref="ArgumentNullException"><paramref name="sourcePath"/> is <c>null</c>.</exception>
- /// <exception cref="ArgumentException"><paramref name="destinationPath"/> is <c>null</c> or contains only whitespace.</exception>
- public IAsyncResult BeginSynchronizeDirectories(string sourcePath, string destinationPath, string searchPattern, AsyncCallback asyncCallback, object state)
- {
- if (sourcePath == null)
- throw new ArgumentNullException("sourcePath");
- if (destinationPath.IsNullOrWhiteSpace())
- throw new ArgumentException("destDir");
- var asyncResult = new SftpSynchronizeDirectoriesAsyncResult(asyncCallback, state);
- ThreadAbstraction.ExecuteThread(() =>
- {
- try
- {
- var result = InternalSynchronizeDirectories(sourcePath, destinationPath, searchPattern, asyncResult);
- asyncResult.SetAsCompleted(result, false);
- }
- catch (Exception exp)
- {
- asyncResult.SetAsCompleted(exp, false);
- }
- });
- return asyncResult;
- }
- /// <summary>
- /// Ends the synchronize directories.
- /// </summary>
- /// <param name="asyncResult">The async result.</param>
- /// <returns>
- /// A list of uploaded files.
- /// </returns>
- /// <exception cref="ArgumentException">The <see cref="IAsyncResult"/> object did not come from the corresponding async method on this type.<para>-or-</para><see cref="EndSynchronizeDirectories(IAsyncResult)"/> was called multiple times with the same <see cref="IAsyncResult"/>.</exception>
- /// <exception cref="SftpPathNotFoundException">The destination path was not found on the remote host.</exception>
- public IEnumerable<FileInfo> EndSynchronizeDirectories(IAsyncResult asyncResult)
- {
- var ar = asyncResult as SftpSynchronizeDirectoriesAsyncResult;
- 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();
- }
- private IEnumerable<FileInfo> InternalSynchronizeDirectories(string sourcePath, string destinationPath, string searchPattern, SftpSynchronizeDirectoriesAsyncResult asynchResult)
- {
- if (!Directory.Exists(sourcePath))
- throw new FileNotFoundException(string.Format("Source directory not found: {0}", sourcePath));
- var uploadedFiles = new List<FileInfo>();
- var sourceDirectory = new DirectoryInfo(sourcePath);
- var sourceFiles = FileSystemAbstraction.EnumerateFiles(sourceDirectory, searchPattern).ToList();
- if (sourceFiles.Count == 0)
- return uploadedFiles;
- #region Existing Files at The Destination
- var destFiles = InternalListDirectory(destinationPath, null);
- var destDict = new Dictionary<string, SftpFile>();
- foreach (var destFile in destFiles)
- {
- if (destFile.IsDirectory)
- continue;
- destDict.Add(destFile.Name, destFile);
- }
- #endregion
- #region Upload the difference
- const Flags uploadFlag = Flags.Write | Flags.Truncate | Flags.CreateNewOrOpen;
- foreach (var localFile in sourceFiles)
- {
- var isDifferent = !destDict.ContainsKey(localFile.Name);
- if (!isDifferent)
- {
- var temp = destDict[localFile.Name];
- // TODO: Use md5 to detect a difference
- //ltang: File exists at the destination => Using filesize to detect the difference
- isDifferent = localFile.Length != temp.Length;
- }
- if (isDifferent)
- {
- var remoteFileName = string.Format(CultureInfo.InvariantCulture, @"{0}/{1}", destinationPath, localFile.Name);
- try
- {
- using (var file = File.OpenRead(localFile.FullName))
- {
- InternalUploadFile(file, remoteFileName, uploadFlag, null, null);
- }
- uploadedFiles.Add(localFile);
- if (asynchResult != null)
- {
- asynchResult.Update(uploadedFiles.Count);
- }
- }
- catch (Exception ex)
- {
- throw new Exception(string.Format("Failed to upload {0} to {1}", localFile.FullName, remoteFileName), ex);
- }
- }
- }
- #endregion
- return uploadedFiles;
- }
- #endregion
- /// <summary>
- /// Internals the list directory.
- /// </summary>
- /// <param name="path">The path.</param>
- /// <param name="listCallback">The list callback.</param>
- /// <returns>
- /// A list of files in the specfied directory.
- /// </returns>
- /// <exception cref="ArgumentNullException"><paramref name="path" /> is <b>null</b>.</exception>
- /// <exception cref="SshConnectionException">Client not connected.</exception>
- private IEnumerable<SftpFile> InternalListDirectory(string path, Action<int> listCallback)
- {
- if (path == null)
- throw new ArgumentNullException("path");
- if (_sftpSession == null)
- throw new SshConnectionException("Client not connected.");
- var fullPath = _sftpSession.GetCanonicalPath(path);
- var handle = _sftpSession.RequestOpenDir(fullPath);
- var basePath = fullPath;
- if (!basePath.EndsWith("/"))
- basePath = string.Format("{0}/", fullPath);
- var result = new List<SftpFile>();
- var files = _sftpSession.RequestReadDir(handle);
- while (files != null)
- {
- result.AddRange(from f in files
- select new SftpFile(_sftpSession, string.Format(CultureInfo.InvariantCulture, "{0}{1}", basePath, f.Key), f.Value));
- // Call callback to report number of files read
- if (listCallback != null)
- {
- // Execute callback on different thread
- ThreadAbstraction.ExecuteThread(() => listCallback(result.Count));
- }
- files = _sftpSession.RequestReadDir(handle);
- }
- _sftpSession.RequestClose(handle);
- return result;
- }
- /// <summary>
- /// Internals the download file.
- /// </summary>
- /// <param name="path">The path.</param>
- /// <param name="output">The output.</param>
- /// <param name="asyncResult">An <see cref="IAsyncResult"/> that references the asynchronous request.</param>
- /// <param name="downloadCallback">The download callback.</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.</exception>
- /// <exception cref="SshConnectionException">Client not connected.</exception>
- private void InternalDownloadFile(string path, Stream output, SftpDownloadAsyncResult asyncResult, Action<ulong> downloadCallback)
- {
- if (output == null)
- throw new ArgumentNullException("output");
- if (path.IsNullOrWhiteSpace())
- throw new ArgumentException("path");
- if (_sftpSession == null)
- throw new SshConnectionException("Client not connected.");
- var fullPath = _sftpSession.GetCanonicalPath(path);
- using (var fileReader = ServiceFactory.CreateSftpFileReader(fullPath, _sftpSession, _bufferSize))
- {
- var totalBytesRead = 0UL;
- while (true)
- {
- // TODO: cancel read ahead when download is canceled by user
- // Cancel download
- if (asyncResult != null && asyncResult.IsDownloadCanceled)
- break;
- var data = fileReader.Read();
- if (data.Length == 0)
- break;
- output.Write(data, 0, data.Length);
- totalBytesRead += (ulong)data.Length;
- if (downloadCallback != null)
- {
- // copy offset to ensure it's not modified between now and execution of callback
- var downloadOffset = totalBytesRead;
- // Execute callback on different thread
- ThreadAbstraction.ExecuteThread(() => { downloadCallback(downloadOffset); });
- }
- }
- }
- }
- /// <summary>
- /// Internals the upload file.
- /// </summary>
- /// <param name="input">The input.</param>
- /// <param name="path">The path.</param>
- /// <param name="flags">The flags.</param>
- /// <param name="asyncResult">An <see cref="IAsyncResult"/> that references the asynchronous request.</param>
- /// <param name="uploadCallback">The upload callback.</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.</exception>
- /// <exception cref="SshConnectionException">Client not connected.</exception>
- private void InternalUploadFile(Stream input, string path, Flags flags, SftpUploadAsyncResult asyncResult, Action<ulong> uploadCallback)
- {
- if (input == null)
- throw new ArgumentNullException("input");
- if (path.IsNullOrWhiteSpace())
- throw new ArgumentException("path");
- if (_sftpSession == null)
- throw new SshConnectionException("Client not connected.");
- var fullPath = _sftpSession.GetCanonicalPath(path);
- var handle = _sftpSession.RequestOpen(fullPath, flags);
- ulong offset = 0;
- // create buffer of optimal length
- var buffer = new byte[_sftpSession.CalculateOptimalWriteLength(_bufferSize, handle)];
- var bytesRead = input.Read(buffer, 0, buffer.Length);
- var expectedResponses = 0;
- var responseReceivedWaitHandle = new AutoResetEvent(false);
- do
- {
- // Cancel upload
- if (asyncResult != null && asyncResult.IsUploadCanceled)
- break;
- if (bytesRead > 0)
- {
- var writtenBytes = offset + (ulong) bytesRead;
- _sftpSession.RequestWrite(handle, offset, buffer, 0, bytesRead, null, s =>
- {
- if (s.StatusCode == StatusCodes.Ok)
- {
- Interlocked.Decrement(ref expectedResponses);
- responseReceivedWaitHandle.Set();
- // Call callback to report number of bytes written
- if (uploadCallback != null)
- {
- // Execute callback on different thread
- ThreadAbstraction.ExecuteThread(() => uploadCallback(writtenBytes));
- }
- }
- });
- Interlocked.Increment(ref expectedResponses);
- offset += (ulong) bytesRead;
- bytesRead = input.Read(buffer, 0, buffer.Length);
- }
- else if (expectedResponses > 0)
- {
- // Wait for expectedResponses to change
- _sftpSession.WaitOnHandle(responseReceivedWaitHandle, OperationTimeout);
- }
- } while (expectedResponses > 0 || bytesRead > 0);
- _sftpSession.RequestClose(handle);
- }
- /// <summary>
- /// Called when client is connected to the server.
- /// </summary>
- protected override void OnConnected()
- {
- base.OnConnected();
- _sftpSession = ServiceFactory.CreateSftpSession(Session, OperationTimeout, ConnectionInfo.Encoding);
- _sftpSession.Connect();
- }
- /// <summary>
- /// Called when client is disconnecting from the server.
- /// </summary>
- protected override void OnDisconnecting()
- {
- base.OnDisconnecting();
- // disconnect, dispose and dereference the SFTP session since we create a new SFTP session
- // on each connect
- var sftpSession = _sftpSession;
- if (sftpSession != null)
- {
- _sftpSession = null;
- sftpSession.Dispose();
- }
- }
- /// <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 resources.</param>
- protected override void Dispose(bool disposing)
- {
- base.Dispose(disposing);
- if (disposing)
- {
- var sftpSession = _sftpSession;
- if (sftpSession != null)
- {
- _sftpSession = null;
- sftpSession.Dispose();
- }
- }
- }
- }
- }
|