SftpClient.cs 108 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153
  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.RequestStat(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="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. using (var fileReader = ServiceFactory.CreateSftpFileReader(fullPath, _sftpSession, _bufferSize))
  1778. {
  1779. var totalBytesRead = 0UL;
  1780. while (true)
  1781. {
  1782. // TODO: cancel read ahead when download is canceled by user
  1783. // Cancel download
  1784. if (asyncResult != null && asyncResult.IsDownloadCanceled)
  1785. break;
  1786. var data = fileReader.Read();
  1787. if (data.Length == 0)
  1788. break;
  1789. output.Write(data, 0, data.Length);
  1790. totalBytesRead += (ulong)data.Length;
  1791. if (downloadCallback != null)
  1792. {
  1793. // copy offset to ensure it's not modified between now and execution of callback
  1794. var downloadOffset = totalBytesRead;
  1795. // Execute callback on different thread
  1796. ThreadAbstraction.ExecuteThread(() => { downloadCallback(downloadOffset); });
  1797. }
  1798. }
  1799. }
  1800. }
  1801. /// <summary>
  1802. /// Internals the upload file.
  1803. /// </summary>
  1804. /// <param name="input">The input.</param>
  1805. /// <param name="path">The path.</param>
  1806. /// <param name="flags">The flags.</param>
  1807. /// <param name="asyncResult">An <see cref="IAsyncResult"/> that references the asynchronous request.</param>
  1808. /// <param name="uploadCallback">The upload callback.</param>
  1809. /// <exception cref="ArgumentNullException"><paramref name="input" /> is <b>null</b>.</exception>
  1810. /// <exception cref="ArgumentException"><paramref name="path" /> is <b>null</b> or contains whitespace.</exception>
  1811. /// <exception cref="SshConnectionException">Client not connected.</exception>
  1812. private void InternalUploadFile(Stream input, string path, Flags flags, SftpUploadAsyncResult asyncResult, Action<ulong> uploadCallback)
  1813. {
  1814. if (input == null)
  1815. throw new ArgumentNullException("input");
  1816. if (path.IsNullOrWhiteSpace())
  1817. throw new ArgumentException("path");
  1818. if (_sftpSession == null)
  1819. throw new SshConnectionException("Client not connected.");
  1820. var fullPath = _sftpSession.GetCanonicalPath(path);
  1821. var handle = _sftpSession.RequestOpen(fullPath, flags);
  1822. ulong offset = 0;
  1823. // create buffer of optimal length
  1824. var buffer = new byte[_sftpSession.CalculateOptimalWriteLength(_bufferSize, handle)];
  1825. var bytesRead = input.Read(buffer, 0, buffer.Length);
  1826. var expectedResponses = 0;
  1827. var responseReceivedWaitHandle = new AutoResetEvent(false);
  1828. do
  1829. {
  1830. // Cancel upload
  1831. if (asyncResult != null && asyncResult.IsUploadCanceled)
  1832. break;
  1833. if (bytesRead > 0)
  1834. {
  1835. var writtenBytes = offset + (ulong) bytesRead;
  1836. _sftpSession.RequestWrite(handle, offset, buffer, 0, bytesRead, null, s =>
  1837. {
  1838. if (s.StatusCode == StatusCodes.Ok)
  1839. {
  1840. Interlocked.Decrement(ref expectedResponses);
  1841. responseReceivedWaitHandle.Set();
  1842. // Call callback to report number of bytes written
  1843. if (uploadCallback != null)
  1844. {
  1845. // Execute callback on different thread
  1846. ThreadAbstraction.ExecuteThread(() => uploadCallback(writtenBytes));
  1847. }
  1848. }
  1849. });
  1850. Interlocked.Increment(ref expectedResponses);
  1851. offset += (ulong) bytesRead;
  1852. bytesRead = input.Read(buffer, 0, buffer.Length);
  1853. }
  1854. else if (expectedResponses > 0)
  1855. {
  1856. // Wait for expectedResponses to change
  1857. _sftpSession.WaitOnHandle(responseReceivedWaitHandle, OperationTimeout);
  1858. }
  1859. } while (expectedResponses > 0 || bytesRead > 0);
  1860. _sftpSession.RequestClose(handle);
  1861. }
  1862. /// <summary>
  1863. /// Called when client is connected to the server.
  1864. /// </summary>
  1865. protected override void OnConnected()
  1866. {
  1867. base.OnConnected();
  1868. _sftpSession = ServiceFactory.CreateSftpSession(Session, OperationTimeout, ConnectionInfo.Encoding);
  1869. _sftpSession.Connect();
  1870. }
  1871. /// <summary>
  1872. /// Called when client is disconnecting from the server.
  1873. /// </summary>
  1874. protected override void OnDisconnecting()
  1875. {
  1876. base.OnDisconnecting();
  1877. // disconnect, dispose and dereference the SFTP session since we create a new SFTP session
  1878. // on each connect
  1879. var sftpSession = _sftpSession;
  1880. if (sftpSession != null)
  1881. {
  1882. _sftpSession = null;
  1883. sftpSession.Dispose();
  1884. }
  1885. }
  1886. /// <summary>
  1887. /// Releases unmanaged and - optionally - managed resources
  1888. /// </summary>
  1889. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  1890. protected override void Dispose(bool disposing)
  1891. {
  1892. base.Dispose(disposing);
  1893. if (disposing)
  1894. {
  1895. var sftpSession = _sftpSession;
  1896. if (sftpSession != null)
  1897. {
  1898. _sftpSession = null;
  1899. sftpSession.Dispose();
  1900. }
  1901. }
  1902. }
  1903. }
  1904. }