SftpClient.cs 130 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625
  1. #nullable enable
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Diagnostics;
  5. using System.Diagnostics.CodeAnalysis;
  6. using System.Globalization;
  7. using System.IO;
  8. using System.Net;
  9. using System.Runtime.CompilerServices;
  10. using System.Runtime.ExceptionServices;
  11. using System.Text;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. using Renci.SshNet.Abstractions;
  15. using Renci.SshNet.Common;
  16. using Renci.SshNet.Sftp;
  17. namespace Renci.SshNet
  18. {
  19. /// <summary>
  20. /// Implementation of the SSH File Transfer Protocol (SFTP) over SSH.
  21. /// </summary>
  22. public class SftpClient : BaseClient, ISftpClient
  23. {
  24. private static readonly Encoding Utf8NoBOM = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true);
  25. /// <summary>
  26. /// Holds the <see cref="ISftpSession"/> instance that is used to communicate to the
  27. /// SFTP server.
  28. /// </summary>
  29. private ISftpSession? _sftpSession;
  30. /// <summary>
  31. /// Holds the operation timeout.
  32. /// </summary>
  33. private int _operationTimeout;
  34. /// <summary>
  35. /// Holds the size of the buffer.
  36. /// </summary>
  37. private uint _bufferSize;
  38. /// <summary>
  39. /// Gets or sets the operation timeout.
  40. /// </summary>
  41. /// <value>
  42. /// The timeout to wait until an operation completes. The default value is negative
  43. /// one (-1) milliseconds, which indicates an infinite timeout period.
  44. /// </value>
  45. /// <exception cref="ArgumentOutOfRangeException"><paramref name="value"/> represents a value that is less than -1 or greater than <see cref="int.MaxValue"/> milliseconds.</exception>
  46. public TimeSpan OperationTimeout
  47. {
  48. get
  49. {
  50. return TimeSpan.FromMilliseconds(_operationTimeout);
  51. }
  52. set
  53. {
  54. _operationTimeout = value.AsTimeout(nameof(OperationTimeout));
  55. if (_sftpSession is { } sftpSession)
  56. {
  57. sftpSession.OperationTimeout = _operationTimeout;
  58. }
  59. }
  60. }
  61. /// <summary>
  62. /// Gets or sets the maximum size of the buffer in bytes.
  63. /// </summary>
  64. /// <value>
  65. /// The size of the buffer. The default buffer size is 32768 bytes (32 KB).
  66. /// </value>
  67. /// <remarks>
  68. /// <para>
  69. /// For write operations, this limits the size of the payload for
  70. /// individual SSH_FXP_WRITE messages. The actual size is always
  71. /// capped at the maximum packet size supported by the peer
  72. /// (minus the size of protocol fields).
  73. /// </para>
  74. /// <para>
  75. /// For read operations, this controls the size of the payload which
  76. /// is requested from the peer in a SSH_FXP_READ message. The peer
  77. /// will send the requested number of bytes in a SSH_FXP_DATA message,
  78. /// possibly split over multiple SSH_MSG_CHANNEL_DATA messages.
  79. /// </para>
  80. /// <para>
  81. /// To optimize the size of the SSH packets sent by the peer,
  82. /// the actual requested size will take into account the size of the
  83. /// SSH_FXP_DATA protocol fields.
  84. /// </para>
  85. /// <para>
  86. /// The size of the each individual SSH_FXP_DATA message is limited to the
  87. /// local maximum packet size of the channel, which is set to <c>64 KB</c>
  88. /// for SSH.NET. However, the peer can limit this even further.
  89. /// </para>
  90. /// </remarks>
  91. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  92. public uint BufferSize
  93. {
  94. get
  95. {
  96. CheckDisposed();
  97. return _bufferSize;
  98. }
  99. set
  100. {
  101. CheckDisposed();
  102. _bufferSize = value;
  103. }
  104. }
  105. /// <summary>
  106. /// Gets a value indicating whether this client is connected to the server and
  107. /// the SFTP session is open.
  108. /// </summary>
  109. /// <value>
  110. /// <see langword="true"/> if this client is connected and the SFTP session is open; otherwise, <see langword="false"/>.
  111. /// </value>
  112. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  113. public override bool IsConnected
  114. {
  115. get
  116. {
  117. return base.IsConnected && _sftpSession?.IsOpen == true;
  118. }
  119. }
  120. /// <summary>
  121. /// Gets remote working directory.
  122. /// </summary>
  123. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  124. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  125. public string WorkingDirectory
  126. {
  127. get
  128. {
  129. CheckDisposed();
  130. if (_sftpSession is null)
  131. {
  132. throw new SshConnectionException("Client not connected.");
  133. }
  134. return _sftpSession.WorkingDirectory;
  135. }
  136. }
  137. /// <summary>
  138. /// Gets sftp protocol version.
  139. /// </summary>
  140. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  141. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  142. public int ProtocolVersion
  143. {
  144. get
  145. {
  146. CheckDisposed();
  147. if (_sftpSession is null)
  148. {
  149. throw new SshConnectionException("Client not connected.");
  150. }
  151. return (int)_sftpSession.ProtocolVersion;
  152. }
  153. }
  154. /// <summary>
  155. /// Gets the current SFTP session.
  156. /// </summary>
  157. /// <value>
  158. /// The current SFTP session.
  159. /// </value>
  160. internal ISftpSession? SftpSession
  161. {
  162. get { return _sftpSession; }
  163. }
  164. #region Constructors
  165. /// <summary>
  166. /// Initializes a new instance of the <see cref="SftpClient"/> class.
  167. /// </summary>
  168. /// <param name="connectionInfo">The connection info.</param>
  169. /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is <see langword="null"/>.</exception>
  170. public SftpClient(ConnectionInfo connectionInfo)
  171. : this(connectionInfo, ownsConnectionInfo: false)
  172. {
  173. }
  174. /// <summary>
  175. /// Initializes a new instance of the <see cref="SftpClient"/> class.
  176. /// </summary>
  177. /// <param name="host">Connection host.</param>
  178. /// <param name="port">Connection port.</param>
  179. /// <param name="username">Authentication username.</param>
  180. /// <param name="password">Authentication password.</param>
  181. /// <exception cref="ArgumentNullException"><paramref name="password"/> is <see langword="null"/>.</exception>
  182. /// <exception cref="ArgumentException"><paramref name="host"/> is invalid. <para>-or-</para> <paramref name="username"/> is <see langword="null"/> or contains only whitespace characters.</exception>
  183. /// <exception cref="ArgumentOutOfRangeException"><paramref name="port"/> is not within <see cref="IPEndPoint.MinPort"/> and <see cref="IPEndPoint.MaxPort"/>.</exception>
  184. [SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope", Justification = "Disposed in Dispose(bool) method.")]
  185. public SftpClient(string host, int port, string username, string password)
  186. : this(new PasswordConnectionInfo(host, port, username, password), ownsConnectionInfo: true)
  187. {
  188. }
  189. /// <summary>
  190. /// Initializes a new instance of the <see cref="SftpClient"/> class.
  191. /// </summary>
  192. /// <param name="host">Connection host.</param>
  193. /// <param name="username">Authentication username.</param>
  194. /// <param name="password">Authentication password.</param>
  195. /// <exception cref="ArgumentNullException"><paramref name="password"/> is <see langword="null"/>.</exception>
  196. /// <exception cref="ArgumentException"><paramref name="host"/> is invalid. <para>-or-</para> <paramref name="username"/> is <see langword="null"/> contains only whitespace characters.</exception>
  197. public SftpClient(string host, string username, string password)
  198. : this(host, ConnectionInfo.DefaultPort, username, password)
  199. {
  200. }
  201. /// <summary>
  202. /// Initializes a new instance of the <see cref="SftpClient"/> class.
  203. /// </summary>
  204. /// <param name="host">Connection host.</param>
  205. /// <param name="port">Connection port.</param>
  206. /// <param name="username">Authentication username.</param>
  207. /// <param name="keyFiles">Authentication private key file(s) .</param>
  208. /// <exception cref="ArgumentNullException"><paramref name="keyFiles"/> is <see langword="null"/>.</exception>
  209. /// <exception cref="ArgumentException"><paramref name="host"/> is invalid. <para>-or-</para> <paramref name="username"/> is <see langword="null"/> or contains only whitespace characters.</exception>
  210. /// <exception cref="ArgumentOutOfRangeException"><paramref name="port"/> is not within <see cref="IPEndPoint.MinPort"/> and <see cref="IPEndPoint.MaxPort"/>.</exception>
  211. [SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope", Justification = "Disposed in Dispose(bool) method.")]
  212. public SftpClient(string host, int port, string username, params IPrivateKeySource[] keyFiles)
  213. : this(new PrivateKeyConnectionInfo(host, port, username, keyFiles), ownsConnectionInfo: true)
  214. {
  215. }
  216. /// <summary>
  217. /// Initializes a new instance of the <see cref="SftpClient"/> class.
  218. /// </summary>
  219. /// <param name="host">Connection host.</param>
  220. /// <param name="username">Authentication username.</param>
  221. /// <param name="keyFiles">Authentication private key file(s) .</param>
  222. /// <exception cref="ArgumentNullException"><paramref name="keyFiles"/> is <see langword="null"/>.</exception>
  223. /// <exception cref="ArgumentException"><paramref name="host"/> is invalid. <para>-or-</para> <paramref name="username"/> is <see langword="null"/> or contains only whitespace characters.</exception>
  224. public SftpClient(string host, string username, params IPrivateKeySource[] keyFiles)
  225. : this(host, ConnectionInfo.DefaultPort, username, keyFiles)
  226. {
  227. }
  228. /// <summary>
  229. /// Initializes a new instance of the <see cref="SftpClient"/> class.
  230. /// </summary>
  231. /// <param name="connectionInfo">The connection info.</param>
  232. /// <param name="ownsConnectionInfo">Specified whether this instance owns the connection info.</param>
  233. /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is <see langword="null"/>.</exception>
  234. /// <remarks>
  235. /// If <paramref name="ownsConnectionInfo"/> is <see langword="true"/>, the connection info will be disposed when this
  236. /// instance is disposed.
  237. /// </remarks>
  238. private SftpClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo)
  239. : this(connectionInfo, ownsConnectionInfo, new ServiceFactory())
  240. {
  241. }
  242. /// <summary>
  243. /// Initializes a new instance of the <see cref="SftpClient"/> class.
  244. /// </summary>
  245. /// <param name="connectionInfo">The connection info.</param>
  246. /// <param name="ownsConnectionInfo">Specified whether this instance owns the connection info.</param>
  247. /// <param name="serviceFactory">The factory to use for creating new services.</param>
  248. /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is <see langword="null"/>.</exception>
  249. /// <exception cref="ArgumentNullException"><paramref name="serviceFactory"/> is <see langword="null"/>.</exception>
  250. /// <remarks>
  251. /// If <paramref name="ownsConnectionInfo"/> is <see langword="true"/>, the connection info will be disposed when this
  252. /// instance is disposed.
  253. /// </remarks>
  254. internal SftpClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo, IServiceFactory serviceFactory)
  255. : base(connectionInfo, ownsConnectionInfo, serviceFactory)
  256. {
  257. _operationTimeout = Timeout.Infinite;
  258. _bufferSize = 1024 * 32;
  259. }
  260. #endregion Constructors
  261. /// <summary>
  262. /// Changes remote directory to path.
  263. /// </summary>
  264. /// <param name="path">New directory path.</param>
  265. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception>
  266. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  267. /// <exception cref="SftpPermissionDeniedException">Permission to change directory denied by remote host. <para>-or-</para> A SSH command was denied by the server.</exception>
  268. /// <exception cref="SftpPathNotFoundException"><paramref name="path"/> was not found on the remote host.</exception>
  269. /// <exception cref="SshException">A SSH error where <see cref="Exception.Message"/> is the message from the remote host.</exception>
  270. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  271. public void ChangeDirectory(string path)
  272. {
  273. CheckDisposed();
  274. ThrowHelper.ThrowIfNull(path);
  275. if (_sftpSession is null)
  276. {
  277. throw new SshConnectionException("Client not connected.");
  278. }
  279. _sftpSession.ChangeDirectory(path);
  280. }
  281. /// <summary>
  282. /// Asynchronously requests to change the current working directory to the specified path.
  283. /// </summary>
  284. /// <param name="path">The new working directory.</param>
  285. /// <param name="cancellationToken">The token to monitor for cancellation requests.</param>
  286. /// <returns>A <see cref="Task"/> that tracks the asynchronous change working directory request.</returns>
  287. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception>
  288. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  289. /// <exception cref="SftpPermissionDeniedException">Permission to change directory denied by remote host. <para>-or-</para> A SSH command was denied by the server.</exception>
  290. /// <exception cref="SftpPathNotFoundException"><paramref name="path"/> was not found on the remote host.</exception>
  291. /// <exception cref="SshException">A SSH error where <see cref="Exception.Message"/> is the message from the remote host.</exception>
  292. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  293. public Task ChangeDirectoryAsync(string path, CancellationToken cancellationToken = default)
  294. {
  295. CheckDisposed();
  296. ThrowHelper.ThrowIfNull(path);
  297. if (_sftpSession is null)
  298. {
  299. throw new SshConnectionException("Client not connected.");
  300. }
  301. cancellationToken.ThrowIfCancellationRequested();
  302. return _sftpSession.ChangeDirectoryAsync(path, cancellationToken);
  303. }
  304. /// <summary>
  305. /// Changes permissions of file(s) to specified mode.
  306. /// </summary>
  307. /// <param name="path">File(s) path, may match multiple files.</param>
  308. /// <param name="mode">The mode.</param>
  309. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception>
  310. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  311. /// <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>
  312. /// <exception cref="SftpPathNotFoundException"><paramref name="path"/> was not found on the remote host.</exception>
  313. /// <exception cref="SshException">A SSH error where <see cref="Exception.Message"/> is the message from the remote host.</exception>
  314. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  315. public void ChangePermissions(string path, short mode)
  316. {
  317. var file = Get(path);
  318. file.SetPermissions(mode);
  319. }
  320. /// <summary>
  321. /// Creates remote directory specified by path.
  322. /// </summary>
  323. /// <param name="path">Directory path to create.</param>
  324. /// <exception cref="ArgumentException"><paramref name="path"/> is <see langword="null"/> or contains only whitespace characters.</exception>
  325. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  326. /// <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>
  327. /// <exception cref="SshException">A SSH error where <see cref="Exception.Message"/> is the message from the remote host.</exception>
  328. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  329. public void CreateDirectory(string path)
  330. {
  331. CheckDisposed();
  332. ThrowHelper.ThrowIfNullOrWhiteSpace(path);
  333. if (_sftpSession is null)
  334. {
  335. throw new SshConnectionException("Client not connected.");
  336. }
  337. var fullPath = _sftpSession.GetCanonicalPath(path);
  338. _sftpSession.RequestMkDir(fullPath);
  339. }
  340. /// <summary>
  341. /// Asynchronously requests to create a remote directory specified by path.
  342. /// </summary>
  343. /// <param name="path">Directory path to create.</param>
  344. /// <param name="cancellationToken">The <see cref="CancellationToken"/> to observe.</param>
  345. /// <returns>A <see cref="Task"/> that represents the asynchronous create directory operation.</returns>
  346. /// <exception cref="ArgumentException"><paramref name="path"/> is <see langword="null"/> or contains only whitespace characters.</exception>
  347. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  348. /// <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>
  349. /// <exception cref="SshException">A SSH error where <see cref="Exception.Message"/> is the message from the remote host.</exception>
  350. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  351. public async Task CreateDirectoryAsync(string path, CancellationToken cancellationToken = default)
  352. {
  353. CheckDisposed();
  354. ThrowHelper.ThrowIfNullOrWhiteSpace(path);
  355. if (_sftpSession is null)
  356. {
  357. throw new SshConnectionException("Client not connected.");
  358. }
  359. var fullPath = await _sftpSession.GetCanonicalPathAsync(path, cancellationToken).ConfigureAwait(false);
  360. await _sftpSession.RequestMkDirAsync(fullPath, cancellationToken).ConfigureAwait(false);
  361. }
  362. /// <summary>
  363. /// Deletes remote directory specified by path.
  364. /// </summary>
  365. /// <param name="path">Directory to be deleted path.</param>
  366. /// <exception cref="ArgumentException"><paramref name="path"/> is <see langword="null"/> or contains only whitespace characters.</exception>
  367. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  368. /// <exception cref="SftpPathNotFoundException"><paramref name="path"/> was not found on the remote host.</exception>
  369. /// <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>
  370. /// <exception cref="SshException">A SSH error where <see cref="Exception.Message"/> is the message from the remote host.</exception>
  371. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  372. public void DeleteDirectory(string path)
  373. {
  374. CheckDisposed();
  375. ThrowHelper.ThrowIfNullOrWhiteSpace(path);
  376. if (_sftpSession is null)
  377. {
  378. throw new SshConnectionException("Client not connected.");
  379. }
  380. var fullPath = _sftpSession.GetCanonicalPath(path);
  381. _sftpSession.RequestRmDir(fullPath);
  382. }
  383. /// <inheritdoc />
  384. public async Task DeleteDirectoryAsync(string path, CancellationToken cancellationToken = default)
  385. {
  386. CheckDisposed();
  387. ThrowHelper.ThrowIfNullOrWhiteSpace(path);
  388. if (_sftpSession is null)
  389. {
  390. throw new SshConnectionException("Client not connected.");
  391. }
  392. cancellationToken.ThrowIfCancellationRequested();
  393. var fullPath = await _sftpSession.GetCanonicalPathAsync(path, cancellationToken).ConfigureAwait(false);
  394. await _sftpSession.RequestRmDirAsync(fullPath, cancellationToken).ConfigureAwait(false);
  395. }
  396. /// <summary>
  397. /// Deletes remote file specified by path.
  398. /// </summary>
  399. /// <param name="path">File to be deleted path.</param>
  400. /// <exception cref="ArgumentException"><paramref name="path"/> is <see langword="null"/> or contains only whitespace characters.</exception>
  401. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  402. /// <exception cref="SftpPathNotFoundException"><paramref name="path"/> was not found on the remote host.</exception>
  403. /// <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>
  404. /// <exception cref="SshException">A SSH error where <see cref="Exception.Message"/> is the message from the remote host.</exception>
  405. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  406. public void DeleteFile(string path)
  407. {
  408. CheckDisposed();
  409. ThrowHelper.ThrowIfNullOrWhiteSpace(path);
  410. if (_sftpSession is null)
  411. {
  412. throw new SshConnectionException("Client not connected.");
  413. }
  414. var fullPath = _sftpSession.GetCanonicalPath(path);
  415. _sftpSession.RequestRemove(fullPath);
  416. }
  417. /// <inheritdoc />
  418. public async Task DeleteFileAsync(string path, CancellationToken cancellationToken)
  419. {
  420. CheckDisposed();
  421. ThrowHelper.ThrowIfNullOrWhiteSpace(path);
  422. if (_sftpSession is null)
  423. {
  424. throw new SshConnectionException("Client not connected.");
  425. }
  426. cancellationToken.ThrowIfCancellationRequested();
  427. var fullPath = await _sftpSession.GetCanonicalPathAsync(path, cancellationToken).ConfigureAwait(false);
  428. await _sftpSession.RequestRemoveAsync(fullPath, cancellationToken).ConfigureAwait(false);
  429. }
  430. /// <summary>
  431. /// Renames remote file from old path to new path.
  432. /// </summary>
  433. /// <param name="oldPath">Path to the old file location.</param>
  434. /// <param name="newPath">Path to the new file location.</param>
  435. /// <exception cref="ArgumentNullException"><paramref name="oldPath"/> is <see langword="null"/>. <para>-or-</para> or <paramref name="newPath"/> is <see langword="null"/>.</exception>
  436. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  437. /// <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>
  438. /// <exception cref="SshException">A SSH error where <see cref="Exception.Message"/> is the message from the remote host.</exception>
  439. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  440. public void RenameFile(string oldPath, string newPath)
  441. {
  442. RenameFile(oldPath, newPath, isPosix: false);
  443. }
  444. /// <summary>
  445. /// Renames remote file from old path to new path.
  446. /// </summary>
  447. /// <param name="oldPath">Path to the old file location.</param>
  448. /// <param name="newPath">Path to the new file location.</param>
  449. /// <param name="isPosix">if set to <see langword="true"/> then perform a posix rename.</param>
  450. /// <exception cref="ArgumentNullException"><paramref name="oldPath" /> is <see langword="null"/>. <para>-or-</para> or <paramref name="newPath" /> is <see langword="null"/>.</exception>
  451. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  452. /// <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>
  453. /// <exception cref="SshException">A SSH error where <see cref="Exception.Message" /> is the message from the remote host.</exception>
  454. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  455. public void RenameFile(string oldPath, string newPath, bool isPosix)
  456. {
  457. CheckDisposed();
  458. ThrowHelper.ThrowIfNull(oldPath);
  459. ThrowHelper.ThrowIfNull(newPath);
  460. if (_sftpSession is null)
  461. {
  462. throw new SshConnectionException("Client not connected.");
  463. }
  464. var oldFullPath = _sftpSession.GetCanonicalPath(oldPath);
  465. var newFullPath = _sftpSession.GetCanonicalPath(newPath);
  466. if (isPosix)
  467. {
  468. _sftpSession.RequestPosixRename(oldFullPath, newFullPath);
  469. }
  470. else
  471. {
  472. _sftpSession.RequestRename(oldFullPath, newFullPath);
  473. }
  474. }
  475. /// <summary>
  476. /// Asynchronously renames remote file from old path to new path.
  477. /// </summary>
  478. /// <param name="oldPath">Path to the old file location.</param>
  479. /// <param name="newPath">Path to the new file location.</param>
  480. /// <param name="cancellationToken">The <see cref="CancellationToken"/> to observe.</param>
  481. /// <returns>A <see cref="Task"/> that represents the asynchronous rename operation.</returns>
  482. /// <exception cref="ArgumentNullException"><paramref name="oldPath"/> is <see langword="null"/>. <para>-or-</para> or <paramref name="newPath"/> is <see langword="null"/>.</exception>
  483. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  484. /// <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>
  485. /// <exception cref="SshException">A SSH error where <see cref="Exception.Message"/> is the message from the remote host.</exception>
  486. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  487. public async Task RenameFileAsync(string oldPath, string newPath, CancellationToken cancellationToken)
  488. {
  489. CheckDisposed();
  490. ThrowHelper.ThrowIfNull(oldPath);
  491. ThrowHelper.ThrowIfNull(newPath);
  492. if (_sftpSession is null)
  493. {
  494. throw new SshConnectionException("Client not connected.");
  495. }
  496. cancellationToken.ThrowIfCancellationRequested();
  497. var oldFullPath = await _sftpSession.GetCanonicalPathAsync(oldPath, cancellationToken).ConfigureAwait(false);
  498. var newFullPath = await _sftpSession.GetCanonicalPathAsync(newPath, cancellationToken).ConfigureAwait(false);
  499. await _sftpSession.RequestRenameAsync(oldFullPath, newFullPath, cancellationToken).ConfigureAwait(false);
  500. }
  501. /// <summary>
  502. /// Creates a symbolic link from old path to new path.
  503. /// </summary>
  504. /// <param name="path">The old path.</param>
  505. /// <param name="linkPath">The new path.</param>
  506. /// <exception cref="ArgumentException"><paramref name="path"/> is <see langword="null"/>. <para>-or-</para> <paramref name="linkPath"/> is <see langword="null"/> or contains only whitespace characters.</exception>
  507. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  508. /// <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>
  509. /// <exception cref="SshException">A SSH error where <see cref="Exception.Message"/> is the message from the remote host.</exception>
  510. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  511. public void SymbolicLink(string path, string linkPath)
  512. {
  513. CheckDisposed();
  514. ThrowHelper.ThrowIfNullOrWhiteSpace(path);
  515. ThrowHelper.ThrowIfNullOrWhiteSpace(linkPath);
  516. if (_sftpSession is null)
  517. {
  518. throw new SshConnectionException("Client not connected.");
  519. }
  520. var fullPath = _sftpSession.GetCanonicalPath(path);
  521. var linkFullPath = _sftpSession.GetCanonicalPath(linkPath);
  522. _sftpSession.RequestSymLink(fullPath, linkFullPath);
  523. }
  524. /// <summary>
  525. /// Retrieves list of files in remote directory.
  526. /// </summary>
  527. /// <param name="path">The path.</param>
  528. /// <param name="listCallback">The list callback.</param>
  529. /// <returns>
  530. /// A list of files.
  531. /// </returns>
  532. /// <exception cref="ArgumentNullException"><paramref name="path" /> is <see langword="null"/>.</exception>
  533. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  534. /// <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>
  535. /// <exception cref="SshException">A SSH error where <see cref="Exception.Message" /> is the message from the remote host.</exception>
  536. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  537. public IEnumerable<ISftpFile> ListDirectory(string path, Action<int>? listCallback = null)
  538. {
  539. CheckDisposed();
  540. return InternalListDirectory(path, asyncResult: null, listCallback);
  541. }
  542. /// <summary>
  543. /// Asynchronously enumerates the files in remote directory.
  544. /// </summary>
  545. /// <param name="path">The path.</param>
  546. /// <param name="cancellationToken">The <see cref="CancellationToken"/> to observe.</param>
  547. /// <returns>
  548. /// An <see cref="IAsyncEnumerable{T}"/> of <see cref="ISftpFile"/> that represents the asynchronous enumeration operation.
  549. /// The enumeration contains an async stream of <see cref="ISftpFile"/> for the files in the directory specified by <paramref name="path" />.
  550. /// </returns>
  551. /// <exception cref="ArgumentNullException"><paramref name="path" /> is <see langword="null"/>.</exception>
  552. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  553. /// <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>
  554. /// <exception cref="SshException">A SSH error where <see cref="Exception.Message" /> is the message from the remote host.</exception>
  555. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  556. public async IAsyncEnumerable<ISftpFile> ListDirectoryAsync(string path, [EnumeratorCancellation] CancellationToken cancellationToken)
  557. {
  558. CheckDisposed();
  559. ThrowHelper.ThrowIfNull(path);
  560. if (_sftpSession is null)
  561. {
  562. throw new SshConnectionException("Client not connected.");
  563. }
  564. cancellationToken.ThrowIfCancellationRequested();
  565. var fullPath = await _sftpSession.GetCanonicalPathAsync(path, cancellationToken).ConfigureAwait(false);
  566. var handle = await _sftpSession.RequestOpenDirAsync(fullPath, cancellationToken).ConfigureAwait(false);
  567. try
  568. {
  569. var basePath = (fullPath[fullPath.Length - 1] == '/') ?
  570. fullPath :
  571. fullPath + '/';
  572. while (true)
  573. {
  574. var files = await _sftpSession.RequestReadDirAsync(handle, cancellationToken).ConfigureAwait(false);
  575. if (files is null)
  576. {
  577. break;
  578. }
  579. foreach (var file in files)
  580. {
  581. yield return new SftpFile(_sftpSession, basePath + file.Key, file.Value);
  582. }
  583. }
  584. }
  585. finally
  586. {
  587. await _sftpSession.RequestCloseAsync(handle, cancellationToken).ConfigureAwait(false);
  588. }
  589. }
  590. /// <summary>
  591. /// Begins an asynchronous operation of retrieving list of files in remote directory.
  592. /// </summary>
  593. /// <param name="path">The path.</param>
  594. /// <param name="asyncCallback">The method to be called when the asynchronous write operation is completed.</param>
  595. /// <param name="state">A user-provided object that distinguishes this particular asynchronous write request from other requests.</param>
  596. /// <param name="listCallback">The list callback.</param>
  597. /// <returns>
  598. /// An <see cref="IAsyncResult" /> that references the asynchronous operation.
  599. /// </returns>
  600. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  601. public IAsyncResult BeginListDirectory(string path, AsyncCallback? asyncCallback, object? state, Action<int>? listCallback = null)
  602. {
  603. CheckDisposed();
  604. var asyncResult = new SftpListDirectoryAsyncResult(asyncCallback, state);
  605. ThreadAbstraction.ExecuteThread(() =>
  606. {
  607. try
  608. {
  609. var result = InternalListDirectory(path, asyncResult, listCallback);
  610. asyncResult.SetAsCompleted(result, completedSynchronously: false);
  611. }
  612. catch (Exception exp)
  613. {
  614. asyncResult.SetAsCompleted(exp, completedSynchronously: false);
  615. }
  616. });
  617. return asyncResult;
  618. }
  619. /// <summary>
  620. /// Ends an asynchronous operation of retrieving list of files in remote directory.
  621. /// </summary>
  622. /// <param name="asyncResult">The pending asynchronous SFTP request.</param>
  623. /// <returns>
  624. /// A list of files.
  625. /// </returns>
  626. /// <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>
  627. public IEnumerable<ISftpFile> EndListDirectory(IAsyncResult asyncResult)
  628. {
  629. if (asyncResult is not SftpListDirectoryAsyncResult ar || ar.EndInvokeCalled)
  630. {
  631. 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.");
  632. }
  633. // Wait for operation to complete, then return result or throw exception
  634. return ar.EndInvoke();
  635. }
  636. /// <summary>
  637. /// Gets reference to remote file or directory.
  638. /// </summary>
  639. /// <param name="path">The path.</param>
  640. /// <returns>
  641. /// A reference to <see cref="ISftpFile"/> file object.
  642. /// </returns>
  643. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  644. /// <exception cref="SftpPathNotFoundException"><paramref name="path"/> was not found on the remote host.</exception>
  645. /// <exception cref="ArgumentNullException"><paramref name="path" /> is <see langword="null"/>.</exception>
  646. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  647. public ISftpFile Get(string path)
  648. {
  649. CheckDisposed();
  650. ThrowHelper.ThrowIfNull(path);
  651. if (_sftpSession is null)
  652. {
  653. throw new SshConnectionException("Client not connected.");
  654. }
  655. var fullPath = _sftpSession.GetCanonicalPath(path);
  656. var attributes = _sftpSession.RequestLStat(fullPath);
  657. return new SftpFile(_sftpSession, fullPath, attributes);
  658. }
  659. /// <summary>
  660. /// Gets reference to remote file or directory.
  661. /// </summary>
  662. /// <param name="path">The path.</param>
  663. /// <param name="cancellationToken">The <see cref="CancellationToken"/> to observe.</param>
  664. /// <returns>
  665. /// A <see cref="Task{ISftpFile}"/> that represents the get operation.
  666. /// The task result contains the reference to <see cref="ISftpFile"/> file object.
  667. /// </returns>
  668. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  669. /// <exception cref="SftpPathNotFoundException"><paramref name="path"/> was not found on the remote host.</exception>
  670. /// <exception cref="ArgumentNullException"><paramref name="path" /> is <see langword="null"/>.</exception>
  671. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  672. public async Task<ISftpFile> GetAsync(string path, CancellationToken cancellationToken)
  673. {
  674. CheckDisposed();
  675. ThrowHelper.ThrowIfNull(path);
  676. if (_sftpSession is null)
  677. {
  678. throw new SshConnectionException("Client not connected.");
  679. }
  680. cancellationToken.ThrowIfCancellationRequested();
  681. var fullPath = await _sftpSession.GetCanonicalPathAsync(path, cancellationToken).ConfigureAwait(false);
  682. var attributes = await _sftpSession.RequestLStatAsync(fullPath, cancellationToken).ConfigureAwait(false);
  683. return new SftpFile(_sftpSession, fullPath, attributes);
  684. }
  685. /// <summary>
  686. /// Checks whether file or directory exists.
  687. /// </summary>
  688. /// <param name="path">The path.</param>
  689. /// <returns>
  690. /// <see langword="true"/> if directory or file exists; otherwise <see langword="false"/>.
  691. /// </returns>
  692. /// <exception cref="ArgumentException"><paramref name="path"/> is <see langword="null"/> or contains only whitespace characters.</exception>
  693. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  694. /// <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>
  695. /// <exception cref="SshException">A SSH error where <see cref="Exception.Message"/> is the message from the remote host.</exception>
  696. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  697. public bool Exists(string path)
  698. {
  699. CheckDisposed();
  700. ThrowHelper.ThrowIfNullOrWhiteSpace(path);
  701. if (_sftpSession is null)
  702. {
  703. throw new SshConnectionException("Client not connected.");
  704. }
  705. var fullPath = _sftpSession.GetCanonicalPath(path);
  706. /*
  707. * Using SSH_FXP_REALPATH is not an alternative as the SFTP specification has not always
  708. * been clear on how the server should respond when the specified path is not present on
  709. * the server:
  710. *
  711. * SSH 1 to 4:
  712. * No mention of how the server should respond if the path is not present on the server.
  713. *
  714. * SSH 5:
  715. * The server SHOULD fail the request if the path is not present on the server.
  716. *
  717. * SSH 6:
  718. * Draft 06: The server SHOULD fail the request if the path is not present on the server.
  719. * Draft 07 to 13: The server MUST NOT fail the request if the path does not exist.
  720. *
  721. * Note that SSH 6 (draft 06 and forward) allows for more control options, but we
  722. * currently only support up to v3.
  723. */
  724. try
  725. {
  726. _ = _sftpSession.RequestLStat(fullPath);
  727. return true;
  728. }
  729. catch (SftpPathNotFoundException)
  730. {
  731. return false;
  732. }
  733. }
  734. /// <summary>
  735. /// Checks whether file or directory exists.
  736. /// </summary>
  737. /// <param name="path">The path.</param>
  738. /// <param name="cancellationToken">The <see cref="CancellationToken"/> to observe.</param>
  739. /// <returns>
  740. /// A <see cref="Task{T}"/> that represents the exists operation.
  741. /// The task result contains <see langword="true"/> if directory or file exists; otherwise <see langword="false"/>.
  742. /// </returns>
  743. /// <exception cref="ArgumentException"><paramref name="path"/> is <see langword="null"/> or contains only whitespace characters.</exception>
  744. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  745. /// <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>
  746. /// <exception cref="SshException">A SSH error where <see cref="Exception.Message"/> is the message from the remote host.</exception>
  747. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  748. public async Task<bool> ExistsAsync(string path, CancellationToken cancellationToken = default)
  749. {
  750. CheckDisposed();
  751. ThrowHelper.ThrowIfNullOrWhiteSpace(path);
  752. if (_sftpSession is null)
  753. {
  754. throw new SshConnectionException("Client not connected.");
  755. }
  756. cancellationToken.ThrowIfCancellationRequested();
  757. var fullPath = await _sftpSession.GetCanonicalPathAsync(path, cancellationToken).ConfigureAwait(false);
  758. /*
  759. * Using SSH_FXP_REALPATH is not an alternative as the SFTP specification has not always
  760. * been clear on how the server should respond when the specified path is not present on
  761. * the server:
  762. *
  763. * SSH 1 to 4:
  764. * No mention of how the server should respond if the path is not present on the server.
  765. *
  766. * SSH 5:
  767. * The server SHOULD fail the request if the path is not present on the server.
  768. *
  769. * SSH 6:
  770. * Draft 06: The server SHOULD fail the request if the path is not present on the server.
  771. * Draft 07 to 13: The server MUST NOT fail the request if the path does not exist.
  772. *
  773. * Note that SSH 6 (draft 06 and forward) allows for more control options, but we
  774. * currently only support up to v3.
  775. */
  776. try
  777. {
  778. _ = await _sftpSession.RequestLStatAsync(fullPath, cancellationToken).ConfigureAwait(false);
  779. return true;
  780. }
  781. catch (SftpPathNotFoundException)
  782. {
  783. return false;
  784. }
  785. }
  786. /// <inheritdoc />
  787. public void DownloadFile(string path, Stream output, Action<ulong>? downloadCallback = null)
  788. {
  789. CheckDisposed();
  790. InternalDownloadFile(path, output, asyncResult: null, downloadCallback);
  791. }
  792. /// <inheritdoc />
  793. public Task DownloadFileAsync(string path, Stream output, CancellationToken cancellationToken = default)
  794. {
  795. CheckDisposed();
  796. return InternalDownloadFileAsync(path, output, cancellationToken);
  797. }
  798. /// <summary>
  799. /// Begins an asynchronous file downloading into the stream.
  800. /// </summary>
  801. /// <param name="path">The path.</param>
  802. /// <param name="output">The output.</param>
  803. /// <returns>
  804. /// An <see cref="IAsyncResult" /> that references the asynchronous operation.
  805. /// </returns>
  806. /// <exception cref="ArgumentNullException"><paramref name="output" /> is <see langword="null"/>.</exception>
  807. /// <exception cref="ArgumentException"><paramref name="path" /> is <see langword="null"/> or contains only whitespace characters.</exception>
  808. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  809. /// <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>
  810. /// <exception cref="SshException">A SSH error where <see cref="Exception.Message" /> is the message from the remote host.</exception>
  811. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  812. /// <remarks>
  813. /// Method calls made by this method to <paramref name="output" />, may under certain conditions result in exceptions thrown by the stream.
  814. /// </remarks>
  815. public IAsyncResult BeginDownloadFile(string path, Stream output)
  816. {
  817. return BeginDownloadFile(path, output, asyncCallback: null, state: null);
  818. }
  819. /// <summary>
  820. /// Begins an asynchronous file downloading into the stream.
  821. /// </summary>
  822. /// <param name="path">The path.</param>
  823. /// <param name="output">The output.</param>
  824. /// <param name="asyncCallback">The method to be called when the asynchronous write operation is completed.</param>
  825. /// <returns>
  826. /// An <see cref="IAsyncResult" /> that references the asynchronous operation.
  827. /// </returns>
  828. /// <exception cref="ArgumentNullException"><paramref name="output" /> is <see langword="null"/>.</exception>
  829. /// <exception cref="ArgumentException"><paramref name="path" /> is <see langword="null"/> or contains only whitespace characters.</exception>
  830. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  831. /// <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>
  832. /// <exception cref="SshException">A SSH error where <see cref="Exception.Message" /> is the message from the remote host.</exception>
  833. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  834. /// <remarks>
  835. /// Method calls made by this method to <paramref name="output" />, may under certain conditions result in exceptions thrown by the stream.
  836. /// </remarks>
  837. public IAsyncResult BeginDownloadFile(string path, Stream output, AsyncCallback? asyncCallback)
  838. {
  839. return BeginDownloadFile(path, output, asyncCallback, state: null);
  840. }
  841. /// <summary>
  842. /// Begins an asynchronous file downloading into the stream.
  843. /// </summary>
  844. /// <param name="path">The path.</param>
  845. /// <param name="output">The output.</param>
  846. /// <param name="asyncCallback">The method to be called when the asynchronous write operation is completed.</param>
  847. /// <param name="state">A user-provided object that distinguishes this particular asynchronous write request from other requests.</param>
  848. /// <param name="downloadCallback">The download callback.</param>
  849. /// <returns>
  850. /// An <see cref="IAsyncResult" /> that references the asynchronous operation.
  851. /// </returns>
  852. /// <exception cref="ArgumentNullException"><paramref name="output" /> is <see langword="null"/>.</exception>
  853. /// <exception cref="ArgumentException"><paramref name="path" /> is <see langword="null"/> or contains only whitespace characters.</exception>
  854. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  855. /// <remarks>
  856. /// Method calls made by this method to <paramref name="output" />, may under certain conditions result in exceptions thrown by the stream.
  857. /// </remarks>
  858. public IAsyncResult BeginDownloadFile(string path, Stream output, AsyncCallback? asyncCallback, object? state, Action<ulong>? downloadCallback = null)
  859. {
  860. CheckDisposed();
  861. ThrowHelper.ThrowIfNullOrWhiteSpace(path);
  862. ThrowHelper.ThrowIfNull(output);
  863. var asyncResult = new SftpDownloadAsyncResult(asyncCallback, state);
  864. ThreadAbstraction.ExecuteThread(() =>
  865. {
  866. try
  867. {
  868. InternalDownloadFile(path, output, asyncResult, downloadCallback);
  869. asyncResult.SetAsCompleted(exception: null, completedSynchronously: false);
  870. }
  871. catch (Exception exp)
  872. {
  873. asyncResult.SetAsCompleted(exp, completedSynchronously: false);
  874. }
  875. });
  876. return asyncResult;
  877. }
  878. /// <summary>
  879. /// Ends an asynchronous file downloading into the stream.
  880. /// </summary>
  881. /// <param name="asyncResult">The pending asynchronous SFTP request.</param>
  882. /// <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>
  883. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  884. /// <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>
  885. /// <exception cref="SftpPathNotFoundException">The path was not found on the remote host.</exception>
  886. /// <exception cref="SshException">A SSH error where <see cref="Exception.Message" /> is the message from the remote host.</exception>
  887. public void EndDownloadFile(IAsyncResult asyncResult)
  888. {
  889. if (asyncResult is not SftpDownloadAsyncResult ar || ar.EndInvokeCalled)
  890. {
  891. 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.");
  892. }
  893. // Wait for operation to complete, then return result or throw exception
  894. ar.EndInvoke();
  895. }
  896. /// <inheritdoc/>
  897. public void UploadFile(Stream input, string path, Action<ulong>? uploadCallback = null)
  898. {
  899. UploadFile(input, path, canOverride: true, uploadCallback);
  900. }
  901. /// <inheritdoc/>
  902. public void UploadFile(Stream input, string path, bool canOverride, Action<ulong>? uploadCallback = null)
  903. {
  904. CheckDisposed();
  905. var flags = Flags.Write | Flags.Truncate;
  906. if (canOverride)
  907. {
  908. flags |= Flags.CreateNewOrOpen;
  909. }
  910. else
  911. {
  912. flags |= Flags.CreateNew;
  913. }
  914. InternalUploadFile(input, path, flags, asyncResult: null, uploadCallback);
  915. }
  916. /// <inheritdoc />
  917. public Task UploadFileAsync(Stream input, string path, CancellationToken cancellationToken = default)
  918. {
  919. CheckDisposed();
  920. return InternalUploadFileAsync(input, path, cancellationToken);
  921. }
  922. /// <summary>
  923. /// Begins an asynchronous uploading the stream into remote file.
  924. /// </summary>
  925. /// <param name="input">Data input stream.</param>
  926. /// <param name="path">Remote file path.</param>
  927. /// <returns>
  928. /// An <see cref="IAsyncResult" /> that references the asynchronous operation.
  929. /// </returns>
  930. /// <exception cref="ArgumentNullException"><paramref name="input" /> is <see langword="null"/>.</exception>
  931. /// <exception cref="ArgumentException"><paramref name="path" /> is <see langword="null"/> or contains only whitespace characters.</exception>
  932. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  933. /// <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>
  934. /// <exception cref="SshException">A SSH error where <see cref="Exception.Message" /> is the message from the remote host.</exception>
  935. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  936. /// <remarks>
  937. /// <para>
  938. /// Method calls made by this method to <paramref name="input" />, may under certain conditions result in exceptions thrown by the stream.
  939. /// </para>
  940. /// <para>
  941. /// If the remote file already exists, it is overwritten and truncated.
  942. /// </para>
  943. /// </remarks>
  944. public IAsyncResult BeginUploadFile(Stream input, string path)
  945. {
  946. return BeginUploadFile(input, path, canOverride: true, asyncCallback: null, state: null);
  947. }
  948. /// <summary>
  949. /// Begins an asynchronous uploading the stream into remote file.
  950. /// </summary>
  951. /// <param name="input">Data input stream.</param>
  952. /// <param name="path">Remote file path.</param>
  953. /// <param name="asyncCallback">The method to be called when the asynchronous write operation is completed.</param>
  954. /// <returns>
  955. /// An <see cref="IAsyncResult" /> that references the asynchronous operation.
  956. /// </returns>
  957. /// <exception cref="ArgumentNullException"><paramref name="input" /> is <see langword="null"/>.</exception>
  958. /// <exception cref="ArgumentException"><paramref name="path" /> is <see langword="null"/> or contains only whitespace characters.</exception>
  959. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  960. /// <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>
  961. /// <exception cref="SshException">A SSH error where <see cref="Exception.Message" /> is the message from the remote host.</exception>
  962. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  963. /// <remarks>
  964. /// <para>
  965. /// Method calls made by this method to <paramref name="input" />, may under certain conditions result in exceptions thrown by the stream.
  966. /// </para>
  967. /// <para>
  968. /// If the remote file already exists, it is overwritten and truncated.
  969. /// </para>
  970. /// </remarks>
  971. public IAsyncResult BeginUploadFile(Stream input, string path, AsyncCallback? asyncCallback)
  972. {
  973. return BeginUploadFile(input, path, canOverride: true, asyncCallback, state: null);
  974. }
  975. /// <summary>
  976. /// Begins an asynchronous uploading the stream into remote file.
  977. /// </summary>
  978. /// <param name="input">Data input stream.</param>
  979. /// <param name="path">Remote file path.</param>
  980. /// <param name="asyncCallback">The method to be called when the asynchronous write operation is completed.</param>
  981. /// <param name="state">A user-provided object that distinguishes this particular asynchronous write request from other requests.</param>
  982. /// <param name="uploadCallback">The upload callback.</param>
  983. /// <returns>
  984. /// An <see cref="IAsyncResult" /> that references the asynchronous operation.
  985. /// </returns>
  986. /// <exception cref="ArgumentNullException"><paramref name="input" /> is <see langword="null"/>.</exception>
  987. /// <exception cref="ArgumentException"><paramref name="path" /> is <see langword="null"/> or contains only whitespace characters.</exception>
  988. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  989. /// <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>
  990. /// <exception cref="SshException">A SSH error where <see cref="Exception.Message" /> is the message from the remote host.</exception>
  991. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  992. /// <remarks>
  993. /// <para>
  994. /// Method calls made by this method to <paramref name="input" />, may under certain conditions result in exceptions thrown by the stream.
  995. /// </para>
  996. /// <para>
  997. /// If the remote file already exists, it is overwritten and truncated.
  998. /// </para>
  999. /// </remarks>
  1000. public IAsyncResult BeginUploadFile(Stream input, string path, AsyncCallback? asyncCallback, object? state, Action<ulong>? uploadCallback = null)
  1001. {
  1002. return BeginUploadFile(input, path, canOverride: true, asyncCallback, state, uploadCallback);
  1003. }
  1004. /// <summary>
  1005. /// Begins an asynchronous uploading the stream into remote file.
  1006. /// </summary>
  1007. /// <param name="input">Data input stream.</param>
  1008. /// <param name="path">Remote file path.</param>
  1009. /// <param name="canOverride">Specified whether an existing file can be overwritten.</param>
  1010. /// <param name="asyncCallback">The method to be called when the asynchronous write operation is completed.</param>
  1011. /// <param name="state">A user-provided object that distinguishes this particular asynchronous write request from other requests.</param>
  1012. /// <param name="uploadCallback">The upload callback.</param>
  1013. /// <returns>
  1014. /// An <see cref="IAsyncResult" /> that references the asynchronous operation.
  1015. /// </returns>
  1016. /// <exception cref="ArgumentNullException"><paramref name="input" /> is <see langword="null"/>.</exception>
  1017. /// <exception cref="ArgumentException"><paramref name="path" /> is <see langword="null"/> or contains only whitespace characters.</exception>
  1018. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1019. /// <remarks>
  1020. /// <para>
  1021. /// Method calls made by this method to <paramref name="input" />, may under certain conditions result in exceptions thrown by the stream.
  1022. /// </para>
  1023. /// <para>
  1024. /// When <paramref name="path"/> refers to an existing file, set <paramref name="canOverride"/> to <see langword="true"/> to overwrite and truncate that file.
  1025. /// If <paramref name="canOverride"/> is <see langword="false"/>, the upload will fail and <see cref="EndUploadFile(IAsyncResult)"/> will throw an
  1026. /// <see cref="SshException"/>.
  1027. /// </para>
  1028. /// </remarks>
  1029. public IAsyncResult BeginUploadFile(Stream input, string path, bool canOverride, AsyncCallback? asyncCallback, object? state, Action<ulong>? uploadCallback = null)
  1030. {
  1031. CheckDisposed();
  1032. ThrowHelper.ThrowIfNull(input);
  1033. ThrowHelper.ThrowIfNullOrWhiteSpace(path);
  1034. var flags = Flags.Write | Flags.Truncate;
  1035. if (canOverride)
  1036. {
  1037. flags |= Flags.CreateNewOrOpen;
  1038. }
  1039. else
  1040. {
  1041. flags |= Flags.CreateNew;
  1042. }
  1043. var asyncResult = new SftpUploadAsyncResult(asyncCallback, state);
  1044. ThreadAbstraction.ExecuteThread(() =>
  1045. {
  1046. try
  1047. {
  1048. InternalUploadFile(input, path, flags, asyncResult, uploadCallback);
  1049. asyncResult.SetAsCompleted(exception: null, completedSynchronously: false);
  1050. }
  1051. catch (Exception exp)
  1052. {
  1053. asyncResult.SetAsCompleted(exception: exp, completedSynchronously: false);
  1054. }
  1055. });
  1056. return asyncResult;
  1057. }
  1058. /// <summary>
  1059. /// Ends an asynchronous uploading the stream into remote file.
  1060. /// </summary>
  1061. /// <param name="asyncResult">The pending asynchronous SFTP request.</param>
  1062. /// <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>
  1063. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  1064. /// <exception cref="SftpPathNotFoundException">The directory of the file was not found on the remote host.</exception>
  1065. /// <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>
  1066. /// <exception cref="SshException">A SSH error where <see cref="Exception.Message" /> is the message from the remote host.</exception>
  1067. public void EndUploadFile(IAsyncResult asyncResult)
  1068. {
  1069. if (asyncResult is not SftpUploadAsyncResult ar || ar.EndInvokeCalled)
  1070. {
  1071. 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.");
  1072. }
  1073. // Wait for operation to complete, then return result or throw exception
  1074. ar.EndInvoke();
  1075. }
  1076. /// <summary>
  1077. /// Gets status using statvfs@openssh.com request.
  1078. /// </summary>
  1079. /// <param name="path">The path.</param>
  1080. /// <returns>
  1081. /// A <see cref="SftpFileSystemInformation"/> instance that contains file status information.
  1082. /// </returns>
  1083. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  1084. /// <exception cref="ArgumentNullException"><paramref name="path" /> is <see langword="null"/>.</exception>
  1085. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1086. public SftpFileSystemInformation GetStatus(string path)
  1087. {
  1088. CheckDisposed();
  1089. ThrowHelper.ThrowIfNull(path);
  1090. if (_sftpSession is null)
  1091. {
  1092. throw new SshConnectionException("Client not connected.");
  1093. }
  1094. var fullPath = _sftpSession.GetCanonicalPath(path);
  1095. return _sftpSession.RequestStatVfs(fullPath);
  1096. }
  1097. /// <summary>
  1098. /// Asynchronously gets status using statvfs@openssh.com request.
  1099. /// </summary>
  1100. /// <param name="path">The path.</param>
  1101. /// <param name="cancellationToken">The <see cref="CancellationToken"/> to observe.</param>
  1102. /// <returns>
  1103. /// A <see cref="Task{SftpFileSystemInformation}"/> that represents the status operation.
  1104. /// The task result contains the <see cref="SftpFileSystemInformation"/> instance that contains file status information.
  1105. /// </returns>
  1106. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  1107. /// <exception cref="ArgumentNullException"><paramref name="path" /> is <see langword="null"/>.</exception>
  1108. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1109. public async Task<SftpFileSystemInformation> GetStatusAsync(string path, CancellationToken cancellationToken)
  1110. {
  1111. CheckDisposed();
  1112. ThrowHelper.ThrowIfNull(path);
  1113. if (_sftpSession is null)
  1114. {
  1115. throw new SshConnectionException("Client not connected.");
  1116. }
  1117. cancellationToken.ThrowIfCancellationRequested();
  1118. var fullPath = await _sftpSession.GetCanonicalPathAsync(path, cancellationToken).ConfigureAwait(false);
  1119. return await _sftpSession.RequestStatVfsAsync(fullPath, cancellationToken).ConfigureAwait(false);
  1120. }
  1121. #region File Methods
  1122. /// <summary>
  1123. /// Appends lines to a file, creating the file if it does not already exist.
  1124. /// </summary>
  1125. /// <param name="path">The file to append the lines to. The file is created if it does not already exist.</param>
  1126. /// <param name="contents">The lines to append to the file.</param>
  1127. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>. <para>-or-</para> <paramref name="contents"/> is <see langword="null"/>.</exception>
  1128. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  1129. /// <exception cref="SftpPathNotFoundException">The specified path is invalid, or its directory was not found on the remote host.</exception>
  1130. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1131. /// <remarks>
  1132. /// The characters are written to the file using UTF-8 encoding without a byte-order mark (BOM).
  1133. /// </remarks>
  1134. public void AppendAllLines(string path, IEnumerable<string> contents)
  1135. {
  1136. CheckDisposed();
  1137. ThrowHelper.ThrowIfNull(contents);
  1138. using (var stream = AppendText(path))
  1139. {
  1140. foreach (var line in contents)
  1141. {
  1142. stream.WriteLine(line);
  1143. }
  1144. }
  1145. }
  1146. /// <summary>
  1147. /// Appends lines to a file by using a specified encoding, creating the file if it does not already exist.
  1148. /// </summary>
  1149. /// <param name="path">The file to append the lines to. The file is created if it does not already exist.</param>
  1150. /// <param name="contents">The lines to append to the file.</param>
  1151. /// <param name="encoding">The character encoding to use.</param>
  1152. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>. <para>-or-</para> <paramref name="contents"/> is <see langword="null"/>. <para>-or-</para> <paramref name="encoding"/> is <see langword="null"/>.</exception>
  1153. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  1154. /// <exception cref="SftpPathNotFoundException">The specified path is invalid, or its directory was not found on the remote host.</exception>
  1155. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1156. public void AppendAllLines(string path, IEnumerable<string> contents, Encoding encoding)
  1157. {
  1158. CheckDisposed();
  1159. ThrowHelper.ThrowIfNull(contents);
  1160. using (var stream = AppendText(path, encoding))
  1161. {
  1162. foreach (var line in contents)
  1163. {
  1164. stream.WriteLine(line);
  1165. }
  1166. }
  1167. }
  1168. /// <summary>
  1169. /// Appends the specified string to the file, creating the file if it does not already exist.
  1170. /// </summary>
  1171. /// <param name="path">The file to append the specified string to.</param>
  1172. /// <param name="contents">The string to append to the file.</param>
  1173. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>. <para>-or-</para> <paramref name="contents"/> is <see langword="null"/>.</exception>
  1174. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  1175. /// <exception cref="SftpPathNotFoundException">The specified path is invalid, or its directory was not found on the remote host.</exception>
  1176. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1177. /// <remarks>
  1178. /// The characters are written to the file using UTF-8 encoding without a Byte-Order Mark (BOM).
  1179. /// </remarks>
  1180. public void AppendAllText(string path, string contents)
  1181. {
  1182. using (var stream = AppendText(path))
  1183. {
  1184. stream.Write(contents);
  1185. }
  1186. }
  1187. /// <summary>
  1188. /// Appends the specified string to the file, creating the file if it does not already exist.
  1189. /// </summary>
  1190. /// <param name="path">The file to append the specified string to.</param>
  1191. /// <param name="contents">The string to append to the file.</param>
  1192. /// <param name="encoding">The character encoding to use.</param>
  1193. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>. <para>-or-</para> <paramref name="contents"/> is <see langword="null"/>. <para>-or-</para> <paramref name="encoding"/> is <see langword="null"/>.</exception>
  1194. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  1195. /// <exception cref="SftpPathNotFoundException">The specified path is invalid, or its directory was not found on the remote host.</exception>
  1196. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1197. public void AppendAllText(string path, string contents, Encoding encoding)
  1198. {
  1199. using (var stream = AppendText(path, encoding))
  1200. {
  1201. stream.Write(contents);
  1202. }
  1203. }
  1204. /// <summary>
  1205. /// Creates a <see cref="StreamWriter"/> that appends UTF-8 encoded text to the specified file,
  1206. /// creating the file if it does not already exist.
  1207. /// </summary>
  1208. /// <param name="path">The path to the file to append to.</param>
  1209. /// <returns>
  1210. /// A <see cref="StreamWriter"/> that appends text to a file using UTF-8 encoding without a
  1211. /// Byte-Order Mark (BOM).
  1212. /// </returns>
  1213. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception>
  1214. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  1215. /// <exception cref="SftpPathNotFoundException">The specified path is invalid, or its directory was not found on the remote host.</exception>
  1216. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1217. public StreamWriter AppendText(string path)
  1218. {
  1219. return AppendText(path, Utf8NoBOM);
  1220. }
  1221. /// <summary>
  1222. /// Creates a <see cref="StreamWriter"/> that appends text to a file using the specified
  1223. /// encoding, creating the file if it does not already exist.
  1224. /// </summary>
  1225. /// <param name="path">The path to the file to append to.</param>
  1226. /// <param name="encoding">The character encoding to use.</param>
  1227. /// <returns>
  1228. /// A <see cref="StreamWriter"/> that appends text to a file using the specified encoding.
  1229. /// </returns>
  1230. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>. <para>-or-</para> <paramref name="encoding"/> is <see langword="null"/>.</exception>
  1231. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  1232. /// <exception cref="SftpPathNotFoundException">The specified path is invalid, or its directory was not found on the remote host.</exception>
  1233. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1234. public StreamWriter AppendText(string path, Encoding encoding)
  1235. {
  1236. CheckDisposed();
  1237. ThrowHelper.ThrowIfNull(encoding);
  1238. return new StreamWriter(new SftpFileStream(_sftpSession, path, FileMode.Append, FileAccess.Write, (int)_bufferSize), encoding);
  1239. }
  1240. /// <summary>
  1241. /// Creates or overwrites a file in the specified path.
  1242. /// </summary>
  1243. /// <param name="path">The path and name of the file to create.</param>
  1244. /// <returns>
  1245. /// A <see cref="SftpFileStream"/> that provides read/write access to the file specified in path.
  1246. /// </returns>
  1247. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception>
  1248. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  1249. /// <exception cref="SftpPathNotFoundException">The specified path is invalid, or its directory was not found on the remote host.</exception>
  1250. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1251. /// <remarks>
  1252. /// If the target file already exists, it is first truncated to zero bytes.
  1253. /// </remarks>
  1254. public SftpFileStream Create(string path)
  1255. {
  1256. CheckDisposed();
  1257. return new SftpFileStream(_sftpSession, path, FileMode.Create, FileAccess.ReadWrite, (int)_bufferSize);
  1258. }
  1259. /// <summary>
  1260. /// Creates or overwrites the specified file.
  1261. /// </summary>
  1262. /// <param name="path">The path and name of the file to create.</param>
  1263. /// <param name="bufferSize">The maximum number of bytes buffered for reads and writes to the file.</param>
  1264. /// <returns>
  1265. /// A <see cref="SftpFileStream"/> that provides read/write access to the file specified in path.
  1266. /// </returns>
  1267. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception>
  1268. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  1269. /// <exception cref="SftpPathNotFoundException">The specified path is invalid, or its directory was not found on the remote host.</exception>
  1270. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1271. /// <remarks>
  1272. /// If the target file already exists, it is first truncated to zero bytes.
  1273. /// </remarks>
  1274. public SftpFileStream Create(string path, int bufferSize)
  1275. {
  1276. CheckDisposed();
  1277. return new SftpFileStream(_sftpSession, path, FileMode.Create, FileAccess.ReadWrite, bufferSize);
  1278. }
  1279. /// <summary>
  1280. /// Creates or opens a file for writing UTF-8 encoded text.
  1281. /// </summary>
  1282. /// <param name="path">The file to be opened for writing.</param>
  1283. /// <returns>
  1284. /// A <see cref="StreamWriter"/> that writes text to a file using UTF-8 encoding without
  1285. /// a Byte-Order Mark (BOM).
  1286. /// </returns>
  1287. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception>
  1288. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  1289. /// <exception cref="SftpPathNotFoundException">The specified path is invalid, or its directory was not found on the remote host.</exception>
  1290. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1291. /// <remarks>
  1292. /// <para>
  1293. /// If the target file already exists, it is overwritten. It is not first truncated to zero bytes.
  1294. /// </para>
  1295. /// <para>
  1296. /// If the target file does not exist, it is created.
  1297. /// </para>
  1298. /// </remarks>
  1299. public StreamWriter CreateText(string path)
  1300. {
  1301. return CreateText(path, Utf8NoBOM);
  1302. }
  1303. /// <summary>
  1304. /// Creates or opens a file for writing text using the specified encoding.
  1305. /// </summary>
  1306. /// <param name="path">The file to be opened for writing.</param>
  1307. /// <param name="encoding">The character encoding to use.</param>
  1308. /// <returns>
  1309. /// A <see cref="StreamWriter"/> that writes to a file using the specified encoding.
  1310. /// </returns>
  1311. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception>
  1312. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  1313. /// <exception cref="SftpPathNotFoundException">The specified path is invalid, or its directory was not found on the remote host.</exception>
  1314. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1315. /// <remarks>
  1316. /// <para>
  1317. /// If the target file already exists, it is overwritten. It is not first truncated to zero bytes.
  1318. /// </para>
  1319. /// <para>
  1320. /// If the target file does not exist, it is created.
  1321. /// </para>
  1322. /// </remarks>
  1323. public StreamWriter CreateText(string path, Encoding encoding)
  1324. {
  1325. CheckDisposed();
  1326. return new StreamWriter(OpenWrite(path), encoding);
  1327. }
  1328. /// <summary>
  1329. /// Deletes the specified file or directory.
  1330. /// </summary>
  1331. /// <param name="path">The name of the file or directory to be deleted. Wildcard characters are not supported.</param>
  1332. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception>
  1333. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  1334. /// <exception cref="SftpPathNotFoundException"><paramref name="path"/> was not found on the remote host.</exception>
  1335. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1336. public void Delete(string path)
  1337. {
  1338. var file = Get(path);
  1339. file.Delete();
  1340. }
  1341. /// <inheritdoc />
  1342. public async Task DeleteAsync(string path, CancellationToken cancellationToken = default)
  1343. {
  1344. var file = await GetAsync(path, cancellationToken).ConfigureAwait(false);
  1345. await file.DeleteAsync(cancellationToken).ConfigureAwait(false);
  1346. }
  1347. /// <summary>
  1348. /// Returns the date and time the specified file or directory was last accessed.
  1349. /// </summary>
  1350. /// <param name="path">The file or directory for which to obtain access date and time information.</param>
  1351. /// <returns>
  1352. /// A <see cref="DateTime"/> structure set to the date and time that the specified file or directory was last accessed.
  1353. /// This value is expressed in local time.
  1354. /// </returns>
  1355. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception>
  1356. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  1357. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1358. public DateTime GetLastAccessTime(string path)
  1359. {
  1360. var file = Get(path);
  1361. return file.LastAccessTime;
  1362. }
  1363. /// <summary>
  1364. /// Returns the date and time, in coordinated universal time (UTC), that the specified file or directory was last accessed.
  1365. /// </summary>
  1366. /// <param name="path">The file or directory for which to obtain access date and time information.</param>
  1367. /// <returns>
  1368. /// A <see cref="DateTime"/> structure set to the date and time that the specified file or directory was last accessed.
  1369. /// This value is expressed in UTC time.
  1370. /// </returns>
  1371. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception>
  1372. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  1373. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1374. public DateTime GetLastAccessTimeUtc(string path)
  1375. {
  1376. var lastAccessTime = GetLastAccessTime(path);
  1377. return lastAccessTime.ToUniversalTime();
  1378. }
  1379. /// <summary>
  1380. /// Returns the date and time the specified file or directory was last written to.
  1381. /// </summary>
  1382. /// <param name="path">The file or directory for which to obtain write date and time information.</param>
  1383. /// <returns>
  1384. /// A <see cref="DateTime"/> structure set to the date and time that the specified file or directory was last written to.
  1385. /// This value is expressed in local time.
  1386. /// </returns>
  1387. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception>
  1388. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  1389. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1390. public DateTime GetLastWriteTime(string path)
  1391. {
  1392. var file = Get(path);
  1393. return file.LastWriteTime;
  1394. }
  1395. /// <summary>
  1396. /// Returns the date and time, in coordinated universal time (UTC), that the specified file or directory was last written to.
  1397. /// </summary>
  1398. /// <param name="path">The file or directory for which to obtain write date and time information.</param>
  1399. /// <returns>
  1400. /// A <see cref="DateTime"/> structure set to the date and time that the specified file or directory was last written to.
  1401. /// This value is expressed in UTC time.
  1402. /// </returns>
  1403. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception>
  1404. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  1405. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1406. public DateTime GetLastWriteTimeUtc(string path)
  1407. {
  1408. var lastWriteTime = GetLastWriteTime(path);
  1409. return lastWriteTime.ToUniversalTime();
  1410. }
  1411. /// <summary>
  1412. /// Opens a <see cref="SftpFileStream"/> on the specified path with read/write access.
  1413. /// </summary>
  1414. /// <param name="path">The file to open.</param>
  1415. /// <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>
  1416. /// <returns>
  1417. /// An unshared <see cref="SftpFileStream"/> that provides access to the specified file, with the specified mode and read/write access.
  1418. /// </returns>
  1419. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception>
  1420. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  1421. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1422. public SftpFileStream Open(string path, FileMode mode)
  1423. {
  1424. return Open(path, mode, FileAccess.ReadWrite);
  1425. }
  1426. /// <summary>
  1427. /// Opens a <see cref="SftpFileStream"/> on the specified path, with the specified mode and access.
  1428. /// </summary>
  1429. /// <param name="path">The file to open.</param>
  1430. /// <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>
  1431. /// <param name="access">A <see cref="FileAccess"/> value that specifies the operations that can be performed on the file.</param>
  1432. /// <returns>
  1433. /// An unshared <see cref="SftpFileStream"/> that provides access to the specified file, with the specified mode and access.
  1434. /// </returns>
  1435. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception>
  1436. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  1437. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1438. public SftpFileStream Open(string path, FileMode mode, FileAccess access)
  1439. {
  1440. CheckDisposed();
  1441. return new SftpFileStream(_sftpSession, path, mode, access, (int)_bufferSize);
  1442. }
  1443. /// <summary>
  1444. /// Asynchronously opens a <see cref="SftpFileStream"/> on the specified path, with the specified mode and access.
  1445. /// </summary>
  1446. /// <param name="path">The file to open.</param>
  1447. /// <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>
  1448. /// <param name="access">A <see cref="FileAccess"/> value that specifies the operations that can be performed on the file.</param>
  1449. /// <param name="cancellationToken">The <see cref="CancellationToken"/> to observe.</param>
  1450. /// <returns>
  1451. /// A <see cref="Task{SftpFileStream}"/> that represents the asynchronous open operation.
  1452. /// The task result contains the <see cref="SftpFileStream"/> that provides access to the specified file, with the specified mode and access.
  1453. /// </returns>
  1454. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception>
  1455. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  1456. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1457. public Task<SftpFileStream> OpenAsync(string path, FileMode mode, FileAccess access, CancellationToken cancellationToken)
  1458. {
  1459. CheckDisposed();
  1460. ThrowHelper.ThrowIfNull(path);
  1461. if (_sftpSession is null)
  1462. {
  1463. throw new SshConnectionException("Client not connected.");
  1464. }
  1465. cancellationToken.ThrowIfCancellationRequested();
  1466. return SftpFileStream.OpenAsync(_sftpSession, path, mode, access, (int)_bufferSize, cancellationToken);
  1467. }
  1468. /// <summary>
  1469. /// Opens an existing file for reading.
  1470. /// </summary>
  1471. /// <param name="path">The file to be opened for reading.</param>
  1472. /// <returns>
  1473. /// A read-only <see cref="SftpFileStream"/> on the specified path.
  1474. /// </returns>
  1475. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception>
  1476. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  1477. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1478. public SftpFileStream OpenRead(string path)
  1479. {
  1480. return Open(path, FileMode.Open, FileAccess.Read);
  1481. }
  1482. /// <summary>
  1483. /// Opens an existing UTF-8 encoded text file for reading.
  1484. /// </summary>
  1485. /// <param name="path">The file to be opened for reading.</param>
  1486. /// <returns>
  1487. /// A <see cref="StreamReader"/> on the specified path.
  1488. /// </returns>
  1489. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception>
  1490. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  1491. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1492. public StreamReader OpenText(string path)
  1493. {
  1494. return new StreamReader(OpenRead(path), Encoding.UTF8);
  1495. }
  1496. /// <summary>
  1497. /// Opens a file for writing.
  1498. /// </summary>
  1499. /// <param name="path">The file to be opened for writing.</param>
  1500. /// <returns>
  1501. /// An unshared <see cref="SftpFileStream"/> object on the specified path with <see cref="FileAccess.Write"/> access.
  1502. /// </returns>
  1503. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception>
  1504. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  1505. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1506. /// <remarks>
  1507. /// If the file does not exist, it is created.
  1508. /// </remarks>
  1509. public SftpFileStream OpenWrite(string path)
  1510. {
  1511. CheckDisposed();
  1512. return new SftpFileStream(_sftpSession, path, FileMode.OpenOrCreate, FileAccess.Write, (int)_bufferSize);
  1513. }
  1514. /// <summary>
  1515. /// Opens a binary file, reads the contents of the file into a byte array, and closes the file.
  1516. /// </summary>
  1517. /// <param name="path">The file to open for reading.</param>
  1518. /// <returns>
  1519. /// A byte array containing the contents of the file.
  1520. /// </returns>
  1521. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception>
  1522. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  1523. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1524. public byte[] ReadAllBytes(string path)
  1525. {
  1526. using (var stream = OpenRead(path))
  1527. {
  1528. var buffer = new byte[stream.Length];
  1529. _ = stream.Read(buffer, 0, buffer.Length);
  1530. return buffer;
  1531. }
  1532. }
  1533. /// <summary>
  1534. /// Opens a text file, reads all lines of the file using UTF-8 encoding, and closes the file.
  1535. /// </summary>
  1536. /// <param name="path">The file to open for reading.</param>
  1537. /// <returns>
  1538. /// A string array containing all lines of the file.
  1539. /// </returns>
  1540. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception>
  1541. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  1542. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1543. public string[] ReadAllLines(string path)
  1544. {
  1545. return ReadAllLines(path, Encoding.UTF8);
  1546. }
  1547. /// <summary>
  1548. /// Opens a file, reads all lines of the file with the specified encoding, and closes the file.
  1549. /// </summary>
  1550. /// <param name="path">The file to open for reading.</param>
  1551. /// <param name="encoding">The encoding applied to the contents of the file.</param>
  1552. /// <returns>
  1553. /// A string array containing all lines of the file.
  1554. /// </returns>
  1555. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception>
  1556. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  1557. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1558. public string[] ReadAllLines(string path, Encoding encoding)
  1559. {
  1560. /*
  1561. * We use the default buffer size for StreamReader - which is 1024 bytes - and the configured buffer size
  1562. * for the SftpFileStream. We may want to revisit this later.
  1563. */
  1564. var lines = new List<string>();
  1565. using (var stream = new StreamReader(OpenRead(path), encoding))
  1566. {
  1567. string? line;
  1568. while ((line = stream.ReadLine()) != null)
  1569. {
  1570. lines.Add(line);
  1571. }
  1572. }
  1573. return lines.ToArray();
  1574. }
  1575. /// <summary>
  1576. /// Opens a text file, reads all lines of the file with the UTF-8 encoding, and closes the file.
  1577. /// </summary>
  1578. /// <param name="path">The file to open for reading.</param>
  1579. /// <returns>
  1580. /// A string containing all lines of the file.
  1581. /// </returns>
  1582. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception>
  1583. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  1584. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1585. public string ReadAllText(string path)
  1586. {
  1587. return ReadAllText(path, Encoding.UTF8);
  1588. }
  1589. /// <summary>
  1590. /// Opens a file, reads all lines of the file with the specified encoding, and closes the file.
  1591. /// </summary>
  1592. /// <param name="path">The file to open for reading.</param>
  1593. /// <param name="encoding">The encoding applied to the contents of the file.</param>
  1594. /// <returns>
  1595. /// A string containing all lines of the file.
  1596. /// </returns>
  1597. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception>
  1598. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  1599. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1600. public string ReadAllText(string path, Encoding encoding)
  1601. {
  1602. /*
  1603. * We use the default buffer size for StreamReader - which is 1024 bytes - and the configured buffer size
  1604. * for the SftpFileStream. We may want to revisit this later.
  1605. */
  1606. using (var stream = new StreamReader(OpenRead(path), encoding))
  1607. {
  1608. return stream.ReadToEnd();
  1609. }
  1610. }
  1611. /// <summary>
  1612. /// Reads the lines of a file with the UTF-8 encoding.
  1613. /// </summary>
  1614. /// <param name="path">The file to read.</param>
  1615. /// <returns>
  1616. /// The lines of the file.
  1617. /// </returns>
  1618. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception>
  1619. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  1620. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1621. public IEnumerable<string> ReadLines(string path)
  1622. {
  1623. return ReadAllLines(path);
  1624. }
  1625. /// <summary>
  1626. /// Read the lines of a file that has a specified encoding.
  1627. /// </summary>
  1628. /// <param name="path">The file to read.</param>
  1629. /// <param name="encoding">The encoding that is applied to the contents of the file.</param>
  1630. /// <returns>
  1631. /// The lines of the file.
  1632. /// </returns>
  1633. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception>
  1634. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  1635. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1636. public IEnumerable<string> ReadLines(string path, Encoding encoding)
  1637. {
  1638. return ReadAllLines(path, encoding);
  1639. }
  1640. /// <summary>
  1641. /// Sets the date and time the specified file was last accessed.
  1642. /// </summary>
  1643. /// <param name="path">The file for which to set the access date and time information.</param>
  1644. /// <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>
  1645. public void SetLastAccessTime(string path, DateTime lastAccessTime)
  1646. {
  1647. var attributes = GetAttributes(path);
  1648. attributes.LastAccessTime = lastAccessTime;
  1649. SetAttributes(path, attributes);
  1650. }
  1651. /// <summary>
  1652. /// Sets the date and time, in coordinated universal time (UTC), that the specified file was last accessed.
  1653. /// </summary>
  1654. /// <param name="path">The file for which to set the access date and time information.</param>
  1655. /// <param name="lastAccessTimeUtc">A <see cref="DateTime"/> containing the value to set for the last access date and time of path. This value is expressed in UTC time.</param>
  1656. public void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc)
  1657. {
  1658. var attributes = GetAttributes(path);
  1659. attributes.LastAccessTimeUtc = lastAccessTimeUtc;
  1660. SetAttributes(path, attributes);
  1661. }
  1662. /// <summary>
  1663. /// Sets the date and time that the specified file was last written to.
  1664. /// </summary>
  1665. /// <param name="path">The file for which to set the date and time information.</param>
  1666. /// <param name="lastWriteTime">A <see cref="DateTime"/> containing the value to set for the last write date and time of path. This value is expressed in local time.</param>
  1667. public void SetLastWriteTime(string path, DateTime lastWriteTime)
  1668. {
  1669. var attributes = GetAttributes(path);
  1670. attributes.LastWriteTime = lastWriteTime;
  1671. SetAttributes(path, attributes);
  1672. }
  1673. /// <summary>
  1674. /// Sets the date and time, in coordinated universal time (UTC), that the specified file was last written to.
  1675. /// </summary>
  1676. /// <param name="path">The file for which to set the date and time information.</param>
  1677. /// <param name="lastWriteTimeUtc">A <see cref="DateTime"/> containing the value to set for the last write date and time of path. This value is expressed in UTC time.</param>
  1678. public void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc)
  1679. {
  1680. var attributes = GetAttributes(path);
  1681. attributes.LastWriteTimeUtc = lastWriteTimeUtc;
  1682. SetAttributes(path, attributes);
  1683. }
  1684. /// <summary>
  1685. /// Writes the specified byte array to the specified file, and closes the file.
  1686. /// </summary>
  1687. /// <param name="path">The file to write to.</param>
  1688. /// <param name="bytes">The bytes to write to the file.</param>
  1689. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception>
  1690. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  1691. /// <exception cref="SftpPathNotFoundException">The specified path is invalid, or its directory was not found on the remote host.</exception>
  1692. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1693. /// <remarks>
  1694. /// <para>
  1695. /// If the target file already exists, it is overwritten. It is not first truncated to zero bytes.
  1696. /// </para>
  1697. /// <para>
  1698. /// If the target file does not exist, it is created.
  1699. /// </para>
  1700. /// </remarks>
  1701. public void WriteAllBytes(string path, byte[] bytes)
  1702. {
  1703. using (var stream = OpenWrite(path))
  1704. {
  1705. stream.Write(bytes, 0, bytes.Length);
  1706. }
  1707. }
  1708. /// <summary>
  1709. /// Writes a collection of strings to the file using the UTF-8 encoding, and closes the file.
  1710. /// </summary>
  1711. /// <param name="path">The file to write to.</param>
  1712. /// <param name="contents">The lines to write to the file.</param>
  1713. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception>
  1714. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  1715. /// <exception cref="SftpPathNotFoundException">The specified path is invalid, or its directory was not found on the remote host.</exception>
  1716. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1717. /// <remarks>
  1718. /// <para>
  1719. /// The characters are written to the file using UTF-8 encoding without a Byte-Order Mark (BOM).
  1720. /// </para>
  1721. /// <para>
  1722. /// If the target file already exists, it is overwritten. It is not first truncated to zero bytes.
  1723. /// </para>
  1724. /// <para>
  1725. /// If the target file does not exist, it is created.
  1726. /// </para>
  1727. /// </remarks>
  1728. public void WriteAllLines(string path, IEnumerable<string> contents)
  1729. {
  1730. WriteAllLines(path, contents, Utf8NoBOM);
  1731. }
  1732. /// <summary>
  1733. /// Write the specified string array to the file using the UTF-8 encoding, and closes the file.
  1734. /// </summary>
  1735. /// <param name="path">The file to write to.</param>
  1736. /// <param name="contents">The string array to write to the file.</param>
  1737. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception>
  1738. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  1739. /// <exception cref="SftpPathNotFoundException">The specified path is invalid, or its directory was not found on the remote host.</exception>
  1740. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1741. /// <remarks>
  1742. /// <para>
  1743. /// The characters are written to the file using UTF-8 encoding without a Byte-Order Mark (BOM).
  1744. /// </para>
  1745. /// <para>
  1746. /// If the target file already exists, it is overwritten. It is not first truncated to zero bytes.
  1747. /// </para>
  1748. /// <para>
  1749. /// If the target file does not exist, it is created.
  1750. /// </para>
  1751. /// </remarks>
  1752. public void WriteAllLines(string path, string[] contents)
  1753. {
  1754. WriteAllLines(path, contents, Utf8NoBOM);
  1755. }
  1756. /// <summary>
  1757. /// Writes a collection of strings to the file using the specified encoding, and closes the file.
  1758. /// </summary>
  1759. /// <param name="path">The file to write to.</param>
  1760. /// <param name="contents">The lines to write to the file.</param>
  1761. /// <param name="encoding">The character encoding to use.</param>
  1762. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception>
  1763. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  1764. /// <exception cref="SftpPathNotFoundException">The specified path is invalid, or its directory was not found on the remote host.</exception>
  1765. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1766. /// <remarks>
  1767. /// <para>
  1768. /// If the target file already exists, it is overwritten. It is not first truncated to zero bytes.
  1769. /// </para>
  1770. /// <para>
  1771. /// If the target file does not exist, it is created.
  1772. /// </para>
  1773. /// </remarks>
  1774. public void WriteAllLines(string path, IEnumerable<string> contents, Encoding encoding)
  1775. {
  1776. using (var stream = CreateText(path, encoding))
  1777. {
  1778. foreach (var line in contents)
  1779. {
  1780. stream.WriteLine(line);
  1781. }
  1782. }
  1783. }
  1784. /// <summary>
  1785. /// Writes the specified string array to the file by using the specified encoding, and closes the file.
  1786. /// </summary>
  1787. /// <param name="path">The file to write to.</param>
  1788. /// <param name="contents">The string array to write to the file.</param>
  1789. /// <param name="encoding">An <see cref="Encoding"/> object that represents the character encoding applied to the string array.</param>
  1790. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception>
  1791. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  1792. /// <exception cref="SftpPathNotFoundException">The specified path is invalid, or its directory was not found on the remote host.</exception>
  1793. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1794. /// <remarks>
  1795. /// <para>
  1796. /// If the target file already exists, it is overwritten. It is not first truncated to zero bytes.
  1797. /// </para>
  1798. /// <para>
  1799. /// If the target file does not exist, it is created.
  1800. /// </para>
  1801. /// </remarks>
  1802. public void WriteAllLines(string path, string[] contents, Encoding encoding)
  1803. {
  1804. using (var stream = CreateText(path, encoding))
  1805. {
  1806. foreach (var line in contents)
  1807. {
  1808. stream.WriteLine(line);
  1809. }
  1810. }
  1811. }
  1812. /// <summary>
  1813. /// Writes the specified string to the file using the UTF-8 encoding, and closes the file.
  1814. /// </summary>
  1815. /// <param name="path">The file to write to.</param>
  1816. /// <param name="contents">The string to write to the file.</param>
  1817. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception>
  1818. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  1819. /// <exception cref="SftpPathNotFoundException">The specified path is invalid, or its directory was not found on the remote host.</exception>
  1820. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1821. /// <remarks>
  1822. /// <para>
  1823. /// The characters are written to the file using UTF-8 encoding without a Byte-Order Mark (BOM).
  1824. /// </para>
  1825. /// <para>
  1826. /// If the target file already exists, it is overwritten. It is not first truncated to zero bytes.
  1827. /// </para>
  1828. /// <para>
  1829. /// If the target file does not exist, it is created.
  1830. /// </para>
  1831. /// </remarks>
  1832. public void WriteAllText(string path, string contents)
  1833. {
  1834. using (var stream = CreateText(path))
  1835. {
  1836. stream.Write(contents);
  1837. }
  1838. }
  1839. /// <summary>
  1840. /// Writes the specified string to the file using the specified encoding, and closes the file.
  1841. /// </summary>
  1842. /// <param name="path">The file to write to.</param>
  1843. /// <param name="contents">The string to write to the file.</param>
  1844. /// <param name="encoding">The encoding to apply to the string.</param>
  1845. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception>
  1846. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  1847. /// <exception cref="SftpPathNotFoundException">The specified path is invalid, or its directory was not found on the remote host.</exception>
  1848. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1849. /// <remarks>
  1850. /// <para>
  1851. /// If the target file already exists, it is overwritten. It is not first truncated to zero bytes.
  1852. /// </para>
  1853. /// <para>
  1854. /// If the target file does not exist, it is created.
  1855. /// </para>
  1856. /// </remarks>
  1857. public void WriteAllText(string path, string contents, Encoding encoding)
  1858. {
  1859. using (var stream = CreateText(path, encoding))
  1860. {
  1861. stream.Write(contents);
  1862. }
  1863. }
  1864. /// <summary>
  1865. /// Gets the <see cref="SftpFileAttributes"/> of the file on the path.
  1866. /// </summary>
  1867. /// <param name="path">The path to the file.</param>
  1868. /// <returns>
  1869. /// The <see cref="SftpFileAttributes"/> of the file on the path.
  1870. /// </returns>
  1871. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception>
  1872. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  1873. /// <exception cref="SftpPathNotFoundException"><paramref name="path"/> was not found on the remote host.</exception>
  1874. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1875. public SftpFileAttributes GetAttributes(string path)
  1876. {
  1877. CheckDisposed();
  1878. if (_sftpSession is null)
  1879. {
  1880. throw new SshConnectionException("Client not connected.");
  1881. }
  1882. var fullPath = _sftpSession.GetCanonicalPath(path);
  1883. return _sftpSession.RequestLStat(fullPath);
  1884. }
  1885. /// <summary>
  1886. /// Sets the specified <see cref="SftpFileAttributes"/> of the file on the specified path.
  1887. /// </summary>
  1888. /// <param name="path">The path to the file.</param>
  1889. /// <param name="fileAttributes">The desired <see cref="SftpFileAttributes"/>.</param>
  1890. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <see langword="null"/>.</exception>
  1891. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  1892. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1893. public void SetAttributes(string path, SftpFileAttributes fileAttributes)
  1894. {
  1895. CheckDisposed();
  1896. if (_sftpSession is null)
  1897. {
  1898. throw new SshConnectionException("Client not connected.");
  1899. }
  1900. var fullPath = _sftpSession.GetCanonicalPath(path);
  1901. _sftpSession.RequestSetStat(fullPath, fileAttributes);
  1902. }
  1903. #endregion // File Methods
  1904. #region SynchronizeDirectories
  1905. /// <summary>
  1906. /// Synchronizes the directories.
  1907. /// </summary>
  1908. /// <param name="sourcePath">The source path.</param>
  1909. /// <param name="destinationPath">The destination path.</param>
  1910. /// <param name="searchPattern">The search pattern.</param>
  1911. /// <returns>
  1912. /// A list of uploaded files.
  1913. /// </returns>
  1914. /// <exception cref="ArgumentNullException"><paramref name="sourcePath"/> is <see langword="null"/>.</exception>
  1915. /// <exception cref="ArgumentException"><paramref name="destinationPath"/> is <see langword="null"/> or contains only whitespace.</exception>
  1916. /// <exception cref="SftpPathNotFoundException"><paramref name="destinationPath"/> was not found on the remote host.</exception>
  1917. /// <exception cref="SshException">If a problem occurs while copying the file.</exception>
  1918. public IEnumerable<FileInfo> SynchronizeDirectories(string sourcePath, string destinationPath, string searchPattern)
  1919. {
  1920. ThrowHelper.ThrowIfNull(sourcePath);
  1921. ThrowHelper.ThrowIfNullOrWhiteSpace(destinationPath);
  1922. return InternalSynchronizeDirectories(sourcePath, destinationPath, searchPattern, asynchResult: null);
  1923. }
  1924. /// <summary>
  1925. /// Begins the synchronize directories.
  1926. /// </summary>
  1927. /// <param name="sourcePath">The source path.</param>
  1928. /// <param name="destinationPath">The destination path.</param>
  1929. /// <param name="searchPattern">The search pattern.</param>
  1930. /// <param name="asyncCallback">The async callback.</param>
  1931. /// <param name="state">The state.</param>
  1932. /// <returns>
  1933. /// An <see cref="IAsyncResult" /> that represents the asynchronous directory synchronization.
  1934. /// </returns>
  1935. /// <exception cref="ArgumentNullException"><paramref name="sourcePath"/> or <paramref name="searchPattern"/> is <see langword="null"/>.</exception>
  1936. /// <exception cref="ArgumentException"><paramref name="destinationPath"/> is <see langword="null"/> or contains only whitespace.</exception>
  1937. /// <exception cref="SshException">If a problem occurs while copying the file.</exception>
  1938. public IAsyncResult BeginSynchronizeDirectories(string sourcePath, string destinationPath, string searchPattern, AsyncCallback? asyncCallback, object? state)
  1939. {
  1940. ThrowHelper.ThrowIfNull(sourcePath);
  1941. ThrowHelper.ThrowIfNullOrWhiteSpace(destinationPath);
  1942. ThrowHelper.ThrowIfNull(searchPattern);
  1943. var asyncResult = new SftpSynchronizeDirectoriesAsyncResult(asyncCallback, state);
  1944. ThreadAbstraction.ExecuteThread(() =>
  1945. {
  1946. try
  1947. {
  1948. var result = InternalSynchronizeDirectories(sourcePath, destinationPath, searchPattern, asyncResult);
  1949. asyncResult.SetAsCompleted(result, completedSynchronously: false);
  1950. }
  1951. catch (Exception exp)
  1952. {
  1953. asyncResult.SetAsCompleted(exp, completedSynchronously: false);
  1954. }
  1955. });
  1956. return asyncResult;
  1957. }
  1958. /// <summary>
  1959. /// Ends the synchronize directories.
  1960. /// </summary>
  1961. /// <param name="asyncResult">The async result.</param>
  1962. /// <returns>
  1963. /// A list of uploaded files.
  1964. /// </returns>
  1965. /// <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>
  1966. /// <exception cref="SftpPathNotFoundException">The destination path was not found on the remote host.</exception>
  1967. public IEnumerable<FileInfo> EndSynchronizeDirectories(IAsyncResult asyncResult)
  1968. {
  1969. if (asyncResult is not SftpSynchronizeDirectoriesAsyncResult ar || ar.EndInvokeCalled)
  1970. {
  1971. 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.");
  1972. }
  1973. // Wait for operation to complete, then return result or throw exception
  1974. return ar.EndInvoke();
  1975. }
  1976. private List<FileInfo> InternalSynchronizeDirectories(string sourcePath, string destinationPath, string searchPattern, SftpSynchronizeDirectoriesAsyncResult? asynchResult)
  1977. {
  1978. if (!Directory.Exists(sourcePath))
  1979. {
  1980. throw new FileNotFoundException(string.Format("Source directory not found: {0}", sourcePath));
  1981. }
  1982. var uploadedFiles = new List<FileInfo>();
  1983. var sourceDirectory = new DirectoryInfo(sourcePath);
  1984. using (var sourceFiles = sourceDirectory.EnumerateFiles(searchPattern).GetEnumerator())
  1985. {
  1986. if (!sourceFiles.MoveNext())
  1987. {
  1988. return uploadedFiles;
  1989. }
  1990. #region Existing Files at The Destination
  1991. var destFiles = InternalListDirectory(destinationPath, asyncResult: null, listCallback: null);
  1992. var destDict = new Dictionary<string, ISftpFile>();
  1993. foreach (var destFile in destFiles)
  1994. {
  1995. if (destFile.IsDirectory)
  1996. {
  1997. continue;
  1998. }
  1999. destDict.Add(destFile.Name, destFile);
  2000. }
  2001. #endregion
  2002. #region Upload the difference
  2003. const Flags uploadFlag = Flags.Write | Flags.Truncate | Flags.CreateNewOrOpen;
  2004. do
  2005. {
  2006. var localFile = sourceFiles.Current;
  2007. if (localFile is null)
  2008. {
  2009. continue;
  2010. }
  2011. var isDifferent = true;
  2012. if (destDict.TryGetValue(localFile.Name, out var remoteFile))
  2013. {
  2014. // File exists at the destination, use filesize to detect if there's a difference
  2015. isDifferent = localFile.Length != remoteFile.Length;
  2016. }
  2017. if (isDifferent)
  2018. {
  2019. var remoteFileName = string.Format(CultureInfo.InvariantCulture, @"{0}/{1}", destinationPath, localFile.Name);
  2020. try
  2021. {
  2022. #pragma warning disable CA2000 // Dispose objects before losing scope; false positive
  2023. using (var file = File.OpenRead(localFile.FullName))
  2024. #pragma warning restore CA2000 // Dispose objects before losing scope; false positive
  2025. {
  2026. InternalUploadFile(file, remoteFileName, uploadFlag, asyncResult: null, uploadCallback: null);
  2027. }
  2028. uploadedFiles.Add(localFile);
  2029. asynchResult?.Update(uploadedFiles.Count);
  2030. }
  2031. catch (Exception ex)
  2032. {
  2033. throw new SshException($"Failed to upload {localFile.FullName} to {remoteFileName}", ex);
  2034. }
  2035. }
  2036. }
  2037. while (sourceFiles.MoveNext());
  2038. }
  2039. #endregion
  2040. return uploadedFiles;
  2041. }
  2042. #endregion
  2043. /// <summary>
  2044. /// Internals the list directory.
  2045. /// </summary>
  2046. /// <param name="path">The path.</param>
  2047. /// <param name="asyncResult">An <see cref="IAsyncResult"/> that references the asynchronous request.</param>
  2048. /// <param name="listCallback">The list callback.</param>
  2049. /// <returns>
  2050. /// A list of files in the specfied directory.
  2051. /// </returns>
  2052. /// <exception cref="ArgumentNullException"><paramref name="path" /> is <see langword="null"/>.</exception>
  2053. /// <exception cref="SshConnectionException">Client not connected.</exception>
  2054. private List<ISftpFile> InternalListDirectory(string path, SftpListDirectoryAsyncResult? asyncResult, Action<int>? listCallback)
  2055. {
  2056. ThrowHelper.ThrowIfNull(path);
  2057. if (_sftpSession is null)
  2058. {
  2059. throw new SshConnectionException("Client not connected.");
  2060. }
  2061. var fullPath = _sftpSession.GetCanonicalPath(path);
  2062. var handle = _sftpSession.RequestOpenDir(fullPath);
  2063. var basePath = fullPath;
  2064. #if NET || NETSTANDARD2_1
  2065. if (!basePath.EndsWith('/'))
  2066. #else
  2067. if (!basePath.EndsWith("/", StringComparison.Ordinal))
  2068. #endif
  2069. {
  2070. basePath = string.Format("{0}/", fullPath);
  2071. }
  2072. var result = new List<ISftpFile>();
  2073. var files = _sftpSession.RequestReadDir(handle);
  2074. while (files is not null)
  2075. {
  2076. foreach (var f in files)
  2077. {
  2078. result.Add(new SftpFile(_sftpSession,
  2079. string.Format(CultureInfo.InvariantCulture, "{0}{1}", basePath, f.Key),
  2080. f.Value));
  2081. }
  2082. asyncResult?.Update(result.Count);
  2083. // Call callback to report number of files read
  2084. if (listCallback is not null)
  2085. {
  2086. // Execute callback on different thread
  2087. ThreadAbstraction.ExecuteThread(() => listCallback(result.Count));
  2088. }
  2089. files = _sftpSession.RequestReadDir(handle);
  2090. }
  2091. _sftpSession.RequestClose(handle);
  2092. return result;
  2093. }
  2094. /// <summary>
  2095. /// Internals the download file.
  2096. /// </summary>
  2097. /// <param name="path">The path.</param>
  2098. /// <param name="output">The output.</param>
  2099. /// <param name="asyncResult">An <see cref="IAsyncResult"/> that references the asynchronous request.</param>
  2100. /// <param name="downloadCallback">The download callback.</param>
  2101. /// <exception cref="ArgumentNullException"><paramref name="output" /> is <see langword="null"/>.</exception>
  2102. /// <exception cref="ArgumentException"><paramref name="path" /> is <see langword="null"/> or contains whitespace.</exception>
  2103. /// <exception cref="SshConnectionException">Client not connected.</exception>
  2104. private void InternalDownloadFile(string path, Stream output, SftpDownloadAsyncResult? asyncResult, Action<ulong>? downloadCallback)
  2105. {
  2106. ThrowHelper.ThrowIfNull(output);
  2107. ThrowHelper.ThrowIfNullOrWhiteSpace(path);
  2108. if (_sftpSession is null)
  2109. {
  2110. throw new SshConnectionException("Client not connected.");
  2111. }
  2112. var fullPath = _sftpSession.GetCanonicalPath(path);
  2113. using (var fileReader = ServiceFactory.CreateSftpFileReader(fullPath, _sftpSession, _bufferSize))
  2114. {
  2115. var totalBytesRead = 0UL;
  2116. while (true)
  2117. {
  2118. // Cancel download
  2119. if (asyncResult is not null && asyncResult.IsDownloadCanceled)
  2120. {
  2121. break;
  2122. }
  2123. var data = fileReader.Read();
  2124. if (data.Length == 0)
  2125. {
  2126. break;
  2127. }
  2128. output.Write(data, 0, data.Length);
  2129. totalBytesRead += (ulong)data.Length;
  2130. asyncResult?.Update(totalBytesRead);
  2131. if (downloadCallback is not null)
  2132. {
  2133. // Copy offset to ensure it's not modified between now and execution of callback
  2134. var downloadOffset = totalBytesRead;
  2135. // Execute callback on different thread
  2136. ThreadAbstraction.ExecuteThread(() => { downloadCallback(downloadOffset); });
  2137. }
  2138. }
  2139. }
  2140. }
  2141. private async Task InternalDownloadFileAsync(string path, Stream output, CancellationToken cancellationToken)
  2142. {
  2143. ThrowHelper.ThrowIfNull(output);
  2144. ThrowHelper.ThrowIfNullOrWhiteSpace(path);
  2145. if (_sftpSession is null)
  2146. {
  2147. throw new SshConnectionException("Client not connected.");
  2148. }
  2149. cancellationToken.ThrowIfCancellationRequested();
  2150. var fullPath = await _sftpSession.GetCanonicalPathAsync(path, cancellationToken).ConfigureAwait(false);
  2151. var openStreamTask = SftpFileStream.OpenAsync(_sftpSession, fullPath, FileMode.Open, FileAccess.Read, (int)_bufferSize, cancellationToken);
  2152. using (var input = await openStreamTask.ConfigureAwait(false))
  2153. {
  2154. await input.CopyToAsync(output, 81920, cancellationToken).ConfigureAwait(false);
  2155. }
  2156. }
  2157. /// <summary>
  2158. /// Internals the upload file.
  2159. /// </summary>
  2160. /// <param name="input">The input.</param>
  2161. /// <param name="path">The path.</param>
  2162. /// <param name="flags">The flags.</param>
  2163. /// <param name="asyncResult">An <see cref="IAsyncResult"/> that references the asynchronous request.</param>
  2164. /// <param name="uploadCallback">The upload callback.</param>
  2165. /// <exception cref="ArgumentNullException"><paramref name="input" /> is <see langword="null"/>.</exception>
  2166. /// <exception cref="ArgumentException"><paramref name="path" /> is <see langword="null"/> or contains whitespace.</exception>
  2167. /// <exception cref="SshConnectionException">Client not connected.</exception>
  2168. private void InternalUploadFile(Stream input, string path, Flags flags, SftpUploadAsyncResult? asyncResult, Action<ulong>? uploadCallback)
  2169. {
  2170. ThrowHelper.ThrowIfNull(input);
  2171. ThrowHelper.ThrowIfNullOrWhiteSpace(path);
  2172. if (_sftpSession is null)
  2173. {
  2174. throw new SshConnectionException("Client not connected.");
  2175. }
  2176. var fullPath = _sftpSession.GetCanonicalPath(path);
  2177. var handle = _sftpSession.RequestOpen(fullPath, flags);
  2178. ulong offset = 0;
  2179. // create buffer of optimal length
  2180. var buffer = new byte[_sftpSession.CalculateOptimalWriteLength(_bufferSize, handle)];
  2181. int bytesRead;
  2182. var expectedResponses = 0;
  2183. // We will send out all the write requests without waiting for each response.
  2184. // Afterwards, we may wait on this handle until all responses are received
  2185. // or an error has occured.
  2186. using var mres = new ManualResetEventSlim(initialState: false);
  2187. ExceptionDispatchInfo? exception = null;
  2188. while ((bytesRead = input.Read(buffer, 0, buffer.Length)) != 0)
  2189. {
  2190. if (asyncResult is not null && asyncResult.IsUploadCanceled)
  2191. {
  2192. break;
  2193. }
  2194. exception?.Throw();
  2195. var writtenBytes = offset + (ulong)bytesRead;
  2196. _ = Interlocked.Increment(ref expectedResponses);
  2197. mres.Reset();
  2198. _sftpSession.RequestWrite(handle, offset, buffer, offset: 0, bytesRead, wait: null, s =>
  2199. {
  2200. var setHandle = false;
  2201. try
  2202. {
  2203. if (Sftp.SftpSession.GetSftpException(s) is Exception ex)
  2204. {
  2205. exception = ExceptionDispatchInfo.Capture(ex);
  2206. }
  2207. if (exception is not null)
  2208. {
  2209. setHandle = true;
  2210. return;
  2211. }
  2212. Debug.Assert(s.StatusCode == StatusCodes.Ok);
  2213. asyncResult?.Update(writtenBytes);
  2214. // Call callback to report number of bytes written
  2215. if (uploadCallback is not null)
  2216. {
  2217. // Execute callback on different thread
  2218. ThreadAbstraction.ExecuteThread(() => uploadCallback(writtenBytes));
  2219. }
  2220. }
  2221. finally
  2222. {
  2223. if (Interlocked.Decrement(ref expectedResponses) == 0 || setHandle)
  2224. {
  2225. mres.Set();
  2226. }
  2227. }
  2228. });
  2229. offset += (ulong)bytesRead;
  2230. }
  2231. // Make sure the read of exception cannot be executed ahead of
  2232. // the read of expectedResponses so that we do not miss an
  2233. // exception.
  2234. if (Volatile.Read(ref expectedResponses) != 0)
  2235. {
  2236. _sftpSession.WaitOnHandle(mres.WaitHandle, _operationTimeout);
  2237. }
  2238. exception?.Throw();
  2239. _sftpSession.RequestClose(handle);
  2240. }
  2241. private async Task InternalUploadFileAsync(Stream input, string path, CancellationToken cancellationToken)
  2242. {
  2243. ThrowHelper.ThrowIfNull(input);
  2244. ThrowHelper.ThrowIfNullOrWhiteSpace(path);
  2245. if (_sftpSession is null)
  2246. {
  2247. throw new SshConnectionException("Client not connected.");
  2248. }
  2249. cancellationToken.ThrowIfCancellationRequested();
  2250. var fullPath = await _sftpSession.GetCanonicalPathAsync(path, cancellationToken).ConfigureAwait(false);
  2251. var openStreamTask = SftpFileStream.OpenAsync(_sftpSession, fullPath, FileMode.Create, FileAccess.Write, (int)_bufferSize, cancellationToken);
  2252. using (var output = await openStreamTask.ConfigureAwait(false))
  2253. {
  2254. await input.CopyToAsync(output, 81920, cancellationToken).ConfigureAwait(false);
  2255. }
  2256. }
  2257. /// <summary>
  2258. /// Called when client is connected to the server.
  2259. /// </summary>
  2260. protected override void OnConnected()
  2261. {
  2262. base.OnConnected();
  2263. _sftpSession?.Dispose();
  2264. _sftpSession = CreateAndConnectToSftpSession();
  2265. }
  2266. /// <summary>
  2267. /// Called when client is disconnecting from the server.
  2268. /// </summary>
  2269. protected override void OnDisconnecting()
  2270. {
  2271. base.OnDisconnecting();
  2272. // disconnect, dispose and dereference the SFTP session since we create a new SFTP session
  2273. // on each connect
  2274. var sftpSession = _sftpSession;
  2275. if (sftpSession is not null)
  2276. {
  2277. _sftpSession = null;
  2278. sftpSession.Dispose();
  2279. }
  2280. }
  2281. /// <summary>
  2282. /// Releases unmanaged and - optionally - managed resources.
  2283. /// </summary>
  2284. /// <param name="disposing"><see langword="true"/> to release both managed and unmanaged resources; <see langword="false"/> to release only unmanaged resources.</param>
  2285. protected override void Dispose(bool disposing)
  2286. {
  2287. base.Dispose(disposing);
  2288. if (disposing)
  2289. {
  2290. var sftpSession = _sftpSession;
  2291. if (sftpSession is not null)
  2292. {
  2293. _sftpSession = null;
  2294. sftpSession.Dispose();
  2295. }
  2296. }
  2297. }
  2298. private ISftpSession CreateAndConnectToSftpSession()
  2299. {
  2300. var sftpSession = ServiceFactory.CreateSftpSession(Session,
  2301. _operationTimeout,
  2302. ConnectionInfo.Encoding,
  2303. ServiceFactory.CreateSftpResponseFactory());
  2304. try
  2305. {
  2306. sftpSession.Connect();
  2307. return sftpSession;
  2308. }
  2309. catch
  2310. {
  2311. sftpSession.Dispose();
  2312. throw;
  2313. }
  2314. }
  2315. }
  2316. }