SftpClient.cs 108 KB

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