SftpClient.cs 126 KB

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