SftpClient.cs 94 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763
  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. namespace Renci.SshNet
  12. {
  13. /// <summary>
  14. /// Implementation of the SSH File Transfer Protocol (SFTP) over SSH.
  15. /// </summary>
  16. public partial class SftpClient : BaseClient
  17. {
  18. /// <summary>
  19. /// Holds the <see cref="SftpSession"/> instance that used to communicate to the
  20. /// SFTP server.
  21. /// </summary>
  22. private SftpSession _sftpSession;
  23. /// <summary>
  24. /// Holds the operation timeout.
  25. /// </summary>
  26. private TimeSpan _operationTimeout;
  27. /// <summary>
  28. /// Holds the size of the buffer.
  29. /// </summary>
  30. private uint _bufferSize;
  31. /// <summary>
  32. /// Gets or sets the operation timeout.
  33. /// </summary>
  34. /// <value>
  35. /// The timeout to wait until an operation completes. The default value is negative
  36. /// one (-1) milliseconds, which indicates an infinite time-out period.
  37. /// </value>
  38. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  39. public TimeSpan OperationTimeout
  40. {
  41. get
  42. {
  43. CheckDisposed();
  44. return _operationTimeout;
  45. }
  46. set
  47. {
  48. CheckDisposed();
  49. _operationTimeout = value;
  50. }
  51. }
  52. /// <summary>
  53. /// Gets or sets the maximum size of the buffer in bytes.
  54. /// </summary>
  55. /// <value>
  56. /// The size of the buffer. The default buffer size is 65536 bytes (64 KB).
  57. /// </value>
  58. /// <remarks>
  59. /// <para>
  60. /// For write operations, this limits the size of the payload for
  61. /// individual SSH_FXP_WRITE messages. The actual size is always
  62. /// capped at the maximum packet size supported by the peer
  63. /// (minus the size of protocol fields).
  64. /// </para>
  65. /// <para>
  66. /// For read operations, this controls the size of the payload which
  67. /// is requested from the peer in each SSH_FXP_READ message. The peer
  68. /// will send the requested number of bytes in one or more SSH_FXP_DATA
  69. /// messages. To optimize the size of the SSH packets sent by the peer,
  70. /// the actual requested size will take into account the size of the
  71. /// SSH_FXP_DATA protocol fields.
  72. /// </para>
  73. /// <para>
  74. /// The size of the each indivual SSH_FXP_DATA message is limited to the
  75. /// local maximum packet size of the channel, which is set to <c>64 KB</c>
  76. /// for SSH.NET. However, the peer can limit this even further.
  77. /// </para>
  78. /// </remarks>
  79. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  80. public uint BufferSize
  81. {
  82. get
  83. {
  84. CheckDisposed();
  85. return _bufferSize;
  86. }
  87. set
  88. {
  89. CheckDisposed();
  90. _bufferSize = value;
  91. }
  92. }
  93. /// <summary>
  94. /// Gets remote working directory.
  95. /// </summary>
  96. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  97. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  98. public string WorkingDirectory
  99. {
  100. get
  101. {
  102. CheckDisposed();
  103. if (_sftpSession == null)
  104. throw new SshConnectionException("Client not connected.");
  105. return _sftpSession.WorkingDirectory;
  106. }
  107. }
  108. /// <summary>
  109. /// Gets sftp protocol version.
  110. /// </summary>
  111. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  112. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  113. public int ProtocolVersion
  114. {
  115. get
  116. {
  117. CheckDisposed();
  118. if (_sftpSession == null)
  119. throw new SshConnectionException("Client not connected.");
  120. return (int) _sftpSession.ProtocolVersion;
  121. }
  122. }
  123. #region Constructors
  124. /// <summary>
  125. /// Initializes a new instance of the <see cref="SftpClient"/> class.
  126. /// </summary>
  127. /// <param name="connectionInfo">The connection info.</param>
  128. /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is <b>null</b>.</exception>
  129. public SftpClient(ConnectionInfo connectionInfo)
  130. : this(connectionInfo, false)
  131. {
  132. }
  133. /// <summary>
  134. /// Initializes a new instance of the <see cref="SftpClient"/> class.
  135. /// </summary>
  136. /// <param name="host">Connection host.</param>
  137. /// <param name="port">Connection port.</param>
  138. /// <param name="username">Authentication username.</param>
  139. /// <param name="password">Authentication password.</param>
  140. /// <exception cref="ArgumentNullException"><paramref name="password"/> is <b>null</b>.</exception>
  141. /// <exception cref="ArgumentException"><paramref name="host"/> is invalid. <para>-or-</para> <paramref name="username"/> is <b>null</b> or contains whitespace characters.</exception>
  142. /// <exception cref="ArgumentOutOfRangeException"><paramref name="port"/> is not within <see cref="F:System.Net.IPEndPoint.MinPort"/> and <see cref="System.Net.IPEndPoint.MaxPort"/>.</exception>
  143. [SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope", Justification = "Disposed in Dispose(bool) method.")]
  144. public SftpClient(string host, int port, string username, string password)
  145. : this(new PasswordConnectionInfo(host, port, username, password), true)
  146. {
  147. }
  148. /// <summary>
  149. /// Initializes a new instance of the <see cref="SftpClient"/> class.
  150. /// </summary>
  151. /// <param name="host">Connection host.</param>
  152. /// <param name="username">Authentication username.</param>
  153. /// <param name="password">Authentication password.</param>
  154. /// <exception cref="ArgumentNullException"><paramref name="password"/> is <b>null</b>.</exception>
  155. /// <exception cref="ArgumentException"><paramref name="host"/> is invalid. <para>-or-</para> <paramref name="username"/> is <b>null</b> contains whitespace characters.</exception>
  156. public SftpClient(string host, string username, string password)
  157. : this(host, ConnectionInfo.DEFAULT_PORT, username, password)
  158. {
  159. }
  160. /// <summary>
  161. /// Initializes a new instance of the <see cref="SftpClient"/> class.
  162. /// </summary>
  163. /// <param name="host">Connection host.</param>
  164. /// <param name="port">Connection port.</param>
  165. /// <param name="username">Authentication username.</param>
  166. /// <param name="keyFiles">Authentication private key file(s) .</param>
  167. /// <exception cref="ArgumentNullException"><paramref name="keyFiles"/> is <b>null</b>.</exception>
  168. /// <exception cref="ArgumentException"><paramref name="host"/> is invalid. <para>-or-</para> <paramref name="username"/> is nu<b>null</b>ll or contains whitespace characters.</exception>
  169. /// <exception cref="ArgumentOutOfRangeException"><paramref name="port"/> is not within <see cref="F:System.Net.IPEndPoint.MinPort"/> and <see cref="System.Net.IPEndPoint.MaxPort"/>.</exception>
  170. [SuppressMessage("Microsoft.Reliability", "CA2000:DisposeObjectsBeforeLosingScope", Justification = "Disposed in Dispose(bool) method.")]
  171. public SftpClient(string host, int port, string username, params PrivateKeyFile[] keyFiles)
  172. : this(new PrivateKeyConnectionInfo(host, port, username, keyFiles), true)
  173. {
  174. }
  175. /// <summary>
  176. /// Initializes a new instance of the <see cref="SftpClient"/> class.
  177. /// </summary>
  178. /// <param name="host">Connection host.</param>
  179. /// <param name="username">Authentication username.</param>
  180. /// <param name="keyFiles">Authentication private key file(s) .</param>
  181. /// <exception cref="ArgumentNullException"><paramref name="keyFiles"/> is <b>null</b>.</exception>
  182. /// <exception cref="ArgumentException"><paramref name="host"/> is invalid. <para>-or-</para> <paramref name="username"/> is <b>null</b> or contains whitespace characters.</exception>
  183. public SftpClient(string host, string username, params PrivateKeyFile[] keyFiles)
  184. : this(host, ConnectionInfo.DEFAULT_PORT, username, keyFiles)
  185. {
  186. }
  187. /// <summary>
  188. /// Initializes a new instance of the <see cref="SftpClient"/> class.
  189. /// </summary>
  190. /// <param name="connectionInfo">The connection info.</param>
  191. /// <param name="ownsConnectionInfo">Specified whether this instance owns the connection info.</param>
  192. /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is null.</exception>
  193. /// <remarks>
  194. /// If <paramref name="ownsConnectionInfo"/> is <c>true</c>, then the
  195. /// connection info will be disposed when this instance is disposed.
  196. /// </remarks>
  197. private SftpClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo)
  198. : base(connectionInfo, ownsConnectionInfo)
  199. {
  200. this.OperationTimeout = new TimeSpan(0, 0, 0, 0, -1);
  201. this.BufferSize = 1024 * 64;
  202. }
  203. #endregion
  204. /// <summary>
  205. /// Changes remote directory to path.
  206. /// </summary>
  207. /// <param name="path">New directory path.</param>
  208. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  209. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  210. /// <exception cref="SftpPermissionDeniedException">Permission to change directory denied by remote host. <para>-or-</para> A SSH command was denied by the server.</exception>
  211. /// <exception cref="SftpPathNotFoundException">The path in <paramref name="path"/> was not found on the remote host.</exception>
  212. /// <exception cref="T:Renci.SshNet.Common.SshException">A SSH error where <see cref="P:System.Exception.Message"/> is the message from the remote host.</exception>
  213. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  214. public void ChangeDirectory(string path)
  215. {
  216. CheckDisposed();
  217. if (path == null)
  218. throw new ArgumentNullException("path");
  219. if (this._sftpSession == null)
  220. throw new SshConnectionException("Client not connected.");
  221. this._sftpSession.ChangeDirectory(path);
  222. }
  223. /// <summary>
  224. /// Changes permissions of file(s) to specified mode.
  225. /// </summary>
  226. /// <param name="path">File(s) path, may match multiple files.</param>
  227. /// <param name="mode">The mode.</param>
  228. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  229. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  230. /// <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>
  231. /// <exception cref="SftpPathNotFoundException">The path in <paramref name="path"/> was not found on the remote host.</exception>
  232. /// <exception cref="T:Renci.SshNet.Common.SshException">A SSH error where <see cref="P:System.Exception.Message"/> is the message from the remote host.</exception>
  233. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  234. public void ChangePermissions(string path, short mode)
  235. {
  236. var file = this.Get(path);
  237. file.SetPermissions(mode);
  238. }
  239. /// <summary>
  240. /// Creates remote directory specified by path.
  241. /// </summary>
  242. /// <param name="path">Directory path to create.</param>
  243. /// <exception cref="ArgumentException"><paramref name="path"/> is <b>null</b> or contains whitespace characters.</exception>
  244. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  245. /// <exception cref="Renci.SshNet.Common.SftpPermissionDeniedException">Permission to create the directory was denied by the remote host. <para>-or-</para> A SSH command was denied by the server.</exception>
  246. /// <exception cref="T:Renci.SshNet.Common.SshException">A SSH error where <see cref="P:System.Exception.Message"/> is the message from the remote host.</exception>
  247. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  248. public void CreateDirectory(string path)
  249. {
  250. CheckDisposed();
  251. if (path.IsNullOrWhiteSpace())
  252. throw new ArgumentException(path);
  253. if (this._sftpSession == null)
  254. throw new SshConnectionException("Client not connected.");
  255. var fullPath = this._sftpSession.GetCanonicalPath(path);
  256. this._sftpSession.RequestMkDir(fullPath);
  257. }
  258. /// <summary>
  259. /// Deletes remote directory specified by path.
  260. /// </summary>
  261. /// <param name="path">Directory to be deleted path.</param>
  262. /// <exception cref="ArgumentException"><paramref name="path"/> is <b>null</b> or contains whitespace characters.</exception>
  263. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  264. /// <exception cref="Renci.SshNet.Common.SftpPermissionDeniedException">Permission to delete the directory was denied by the remote host. <para>-or-</para> A SSH command was denied by the server.</exception>
  265. /// <exception cref="T:Renci.SshNet.Common.SshException">A SSH error where <see cref="P:System.Exception.Message"/> is the message from the remote host.</exception>
  266. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  267. public void DeleteDirectory(string path)
  268. {
  269. CheckDisposed();
  270. if (path.IsNullOrWhiteSpace())
  271. throw new ArgumentException("path");
  272. if (this._sftpSession == null)
  273. throw new SshConnectionException("Client not connected.");
  274. var fullPath = this._sftpSession.GetCanonicalPath(path);
  275. this._sftpSession.RequestRmDir(fullPath);
  276. }
  277. /// <summary>
  278. /// Deletes remote file specified by path.
  279. /// </summary>
  280. /// <param name="path">File to be deleted path.</param>
  281. /// <exception cref="ArgumentException"><paramref name="path"/> is <b>null</b> or contains whitespace characters.</exception>
  282. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  283. /// <exception cref="Renci.SshNet.Common.SftpPermissionDeniedException">Permission to delete the file was denied by the remote host. <para>-or-</para> A SSH command was denied by the server.</exception>
  284. /// <exception cref="T:Renci.SshNet.Common.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 DeleteFile(string path)
  287. {
  288. CheckDisposed();
  289. if (path.IsNullOrWhiteSpace())
  290. throw new ArgumentException("path");
  291. if (this._sftpSession == null)
  292. throw new SshConnectionException("Client not connected.");
  293. var fullPath = this._sftpSession.GetCanonicalPath(path);
  294. this._sftpSession.RequestRemove(fullPath);
  295. }
  296. /// <summary>
  297. /// Renames remote file from old path to new path.
  298. /// </summary>
  299. /// <param name="oldPath">Path to the old file location.</param>
  300. /// <param name="newPath">Path to the new file location.</param>
  301. /// <exception cref="ArgumentNullException"><paramref name="oldPath"/> is <b>null</b>. <para>-or-</para> or <paramref name="newPath"/> is <b>null</b>.</exception>
  302. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  303. /// <exception cref="Renci.SshNet.Common.SftpPermissionDeniedException">Permission to rename the file was denied by the remote host. <para>-or-</para> A SSH command was denied by the server.</exception>
  304. /// <exception cref="T:Renci.SshNet.Common.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 RenameFile(string oldPath, string newPath)
  307. {
  308. this.RenameFile(oldPath, newPath, false);
  309. }
  310. /// <summary>
  311. /// Renames remote file from old path to new path.
  312. /// </summary>
  313. /// <param name="oldPath">Path to the old file location.</param>
  314. /// <param name="newPath">Path to the new file location.</param>
  315. /// <param name="isPosix">if set to <c>true</c> then perform a posix rename.</param>
  316. /// <exception cref="ArgumentNullException"><paramref name="oldPath" /> is <b>null</b>. <para>-or-</para> or <paramref name="newPath" /> is <b>null</b>.</exception>
  317. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  318. /// <exception cref="Renci.SshNet.Common.SftpPermissionDeniedException">Permission to rename the file was denied by the remote host. <para>-or-</para> A SSH command was denied by the server.</exception>
  319. /// <exception cref="T:Renci.SshNet.Common.SshException">A SSH error where <see cref="P:System.Exception.Message" /> is the message from the remote host.</exception>
  320. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  321. public void RenameFile(string oldPath, string newPath, bool isPosix)
  322. {
  323. CheckDisposed();
  324. if (oldPath == null)
  325. throw new ArgumentNullException("oldPath");
  326. if (newPath == null)
  327. throw new ArgumentNullException("newPath");
  328. if (this._sftpSession == null)
  329. throw new SshConnectionException("Client not connected.");
  330. var oldFullPath = this._sftpSession.GetCanonicalPath(oldPath);
  331. var newFullPath = this._sftpSession.GetCanonicalPath(newPath);
  332. if (isPosix)
  333. {
  334. this._sftpSession.RequestPosixRename(oldFullPath, newFullPath);
  335. }
  336. else
  337. {
  338. this._sftpSession.RequestRename(oldFullPath, newFullPath);
  339. }
  340. }
  341. /// <summary>
  342. /// Creates a symbolic link from old path to new path.
  343. /// </summary>
  344. /// <param name="path">The old path.</param>
  345. /// <param name="linkPath">The new path.</param>
  346. /// <exception cref="ArgumentException"><paramref name="path"/> is <b>null</b>. <para>-or-</para> <paramref name="linkPath"/> is <b>null</b> or contains whitespace characters.</exception>
  347. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  348. /// <exception cref="Renci.SshNet.Common.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>
  349. /// <exception cref="T:Renci.SshNet.Common.SshException">A SSH error where <see cref="P:System.Exception.Message"/> is the message from the remote host.</exception>
  350. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  351. public void SymbolicLink(string path, string linkPath)
  352. {
  353. CheckDisposed();
  354. if (path.IsNullOrWhiteSpace())
  355. throw new ArgumentException("path");
  356. if (linkPath.IsNullOrWhiteSpace())
  357. throw new ArgumentException("linkPath");
  358. if (this._sftpSession == null)
  359. throw new SshConnectionException("Client not connected.");
  360. var fullPath = this._sftpSession.GetCanonicalPath(path);
  361. var linkFullPath = this._sftpSession.GetCanonicalPath(linkPath);
  362. this._sftpSession.RequestSymLink(fullPath, linkFullPath);
  363. }
  364. /// <summary>
  365. /// Retrieves list of files in remote directory.
  366. /// </summary>
  367. /// <param name="path">The path.</param>
  368. /// <param name="listCallback">The list callback.</param>
  369. /// <returns>
  370. /// List of directory entries
  371. /// </returns>
  372. /// <exception cref="ArgumentNullException"><paramref name="path" /> is <b>null</b>.</exception>
  373. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  374. /// <exception cref="Renci.SshNet.Common.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>
  375. /// <exception cref="T:Renci.SshNet.Common.SshException">A SSH error where <see cref="P:System.Exception.Message" /> is the message from the remote host.</exception>
  376. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  377. public IEnumerable<SftpFile> ListDirectory(string path, Action<int> listCallback = null)
  378. {
  379. CheckDisposed();
  380. return InternalListDirectory(path, listCallback);
  381. }
  382. /// <summary>
  383. /// Begins an asynchronous operation of retrieving list of files in remote directory.
  384. /// </summary>
  385. /// <param name="path">The path.</param>
  386. /// <param name="asyncCallback">The method to be called when the asynchronous write operation is completed.</param>
  387. /// <param name="state">A user-provided object that distinguishes this particular asynchronous write request from other requests.</param>
  388. /// <param name="listCallback">The list callback.</param>
  389. /// <returns>
  390. /// An <see cref="IAsyncResult" /> that references the asynchronous operation.
  391. /// </returns>
  392. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  393. public IAsyncResult BeginListDirectory(string path, AsyncCallback asyncCallback, object state, Action<int> listCallback = null)
  394. {
  395. CheckDisposed();
  396. var asyncResult = new SftpListDirectoryAsyncResult(asyncCallback, state);
  397. this.ExecuteThread(() =>
  398. {
  399. try
  400. {
  401. var result = this.InternalListDirectory(path, count =>
  402. {
  403. asyncResult.Update(count);
  404. if (listCallback != null)
  405. {
  406. listCallback(count);
  407. }
  408. });
  409. asyncResult.SetAsCompleted(result, false);
  410. }
  411. catch (Exception exp)
  412. {
  413. asyncResult.SetAsCompleted(exp, false);
  414. }
  415. });
  416. return asyncResult;
  417. }
  418. /// <summary>
  419. /// Ends an asynchronous operation of retrieving list of files in remote directory.
  420. /// </summary>
  421. /// <param name="asyncResult">The pending asynchronous SFTP request.</param>
  422. /// <returns>
  423. /// List of files
  424. /// </returns>
  425. /// <exception cref="ArgumentException">The IAsyncResult object (<paramref name="asyncResult"/>) did not come from the corresponding async method on this type. <para>-or-</para> EndExecute was called multiple times with the same IAsyncResult.</exception>
  426. public IEnumerable<SftpFile> EndListDirectory(IAsyncResult asyncResult)
  427. {
  428. var ar = asyncResult as SftpListDirectoryAsyncResult;
  429. if (ar == null || ar.EndInvokeCalled)
  430. 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.");
  431. // Wait for operation to complete, then return result or throw exception
  432. return ar.EndInvoke();
  433. }
  434. /// <summary>
  435. /// Gets reference to remote file or directory.
  436. /// </summary>
  437. /// <param name="path">The path.</param>
  438. /// <returns>Reference to <see cref="Renci.SshNet.Sftp.SftpFile"/> file object.</returns>
  439. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  440. /// <exception cref="ArgumentNullException"><paramref name="path" /> is <b>null</b>.</exception>
  441. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  442. public SftpFile Get(string path)
  443. {
  444. CheckDisposed();
  445. if (path == null)
  446. throw new ArgumentNullException("path");
  447. if (this._sftpSession == null)
  448. throw new SshConnectionException("Client not connected.");
  449. var fullPath = this._sftpSession.GetCanonicalPath(path);
  450. var attributes = this._sftpSession.RequestLStat(fullPath);
  451. return new SftpFile(this._sftpSession, fullPath, attributes);
  452. }
  453. /// <summary>
  454. /// Checks whether file pr directory exists;
  455. /// </summary>
  456. /// <param name="path">The path.</param>
  457. /// <returns><c>true</c> if directory or file exists; otherwise <c>false</c>.</returns>
  458. /// <exception cref="ArgumentException"><paramref name="path"/> is <b>null</b> or contains whitespace characters.</exception>
  459. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  460. /// <exception cref="Renci.SshNet.Common.SftpPermissionDeniedException">Permission to perform the operation was denied by the remote host. <para>-or-</para> A SSH command was denied by the server.</exception>
  461. /// <exception cref="T:Renci.SshNet.Common.SshException">A SSH error where <see cref="P:System.Exception.Message"/> is the message from the remote host.</exception>
  462. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  463. public bool Exists(string path)
  464. {
  465. CheckDisposed();
  466. if (path.IsNullOrWhiteSpace())
  467. throw new ArgumentException("path");
  468. if (this._sftpSession == null)
  469. throw new SshConnectionException("Client not connected.");
  470. var fullPath = this._sftpSession.GetFullRemotePath(path);
  471. if (this._sftpSession.RequestRealPath(fullPath, true) == null)
  472. {
  473. return false;
  474. }
  475. return true;
  476. }
  477. /// <summary>
  478. /// Downloads remote file specified by the path into the stream.
  479. /// </summary>
  480. /// <param name="path">File to download.</param>
  481. /// <param name="output">Stream to write the file into.</param>
  482. /// <param name="downloadCallback">The download callback.</param>
  483. /// <exception cref="ArgumentNullException"><paramref name="output" /> is <b>null</b>.</exception>
  484. /// <exception cref="ArgumentException"><paramref name="path" /> is <b>null</b> or contains whitespace characters.</exception>
  485. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  486. /// <exception cref="Renci.SshNet.Common.SftpPermissionDeniedException">Permission to perform the operation was denied by the remote host. <para>-or-</para> A SSH command was denied by the server.</exception>
  487. /// <exception cref="T:Renci.SshNet.Common.SshException">A SSH error where <see cref="P:System.Exception.Message" /> is the message from the remote host.</exception>
  488. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  489. /// <remarks>
  490. /// Method calls made by this method to <paramref name="output" />, may under certain conditions result in exceptions thrown by the stream.
  491. /// </remarks>
  492. public void DownloadFile(string path, Stream output, Action<ulong> downloadCallback = null)
  493. {
  494. CheckDisposed();
  495. this.InternalDownloadFile(path, output, null, downloadCallback);
  496. }
  497. /// <summary>
  498. /// Begins an asynchronous file downloading into the stream.
  499. /// </summary>
  500. /// <param name="path">The path.</param>
  501. /// <param name="output">The output.</param>
  502. /// <returns>
  503. /// An <see cref="IAsyncResult" /> that references the asynchronous operation.
  504. /// </returns>
  505. /// <exception cref="ArgumentNullException"><paramref name="output" /> is <b>null</b>.</exception>
  506. /// <exception cref="ArgumentException"><paramref name="path" /> is <b>null</b> or contains whitespace characters.</exception>
  507. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  508. /// <exception cref="Renci.SshNet.Common.SftpPermissionDeniedException">Permission to perform the operation was denied by the remote host. <para>-or-</para> A SSH command was denied by the server.</exception>
  509. /// <exception cref="T:Renci.SshNet.Common.SshException">A SSH error where <see cref="P:System.Exception.Message" /> is the message from the remote host.</exception>
  510. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  511. /// <remarks>
  512. /// Method calls made by this method to <paramref name="output" />, may under certain conditions result in exceptions thrown by the stream.
  513. /// </remarks>
  514. public IAsyncResult BeginDownloadFile(string path, Stream output)
  515. {
  516. return this.BeginDownloadFile(path, output, null, null, null);
  517. }
  518. /// <summary>
  519. /// Begins an asynchronous file downloading into the stream.
  520. /// </summary>
  521. /// <param name="path">The path.</param>
  522. /// <param name="output">The output.</param>
  523. /// <param name="asyncCallback">The method to be called when the asynchronous write operation is completed.</param>
  524. /// <returns>
  525. /// An <see cref="IAsyncResult" /> that references the asynchronous operation.
  526. /// </returns>
  527. /// <exception cref="ArgumentNullException"><paramref name="output" /> is <b>null</b>.</exception>
  528. /// <exception cref="ArgumentException"><paramref name="path" /> is <b>null</b> or contains whitespace characters.</exception>
  529. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  530. /// <exception cref="Renci.SshNet.Common.SftpPermissionDeniedException">Permission to perform the operation was denied by the remote host. <para>-or-</para> A SSH command was denied by the server.</exception>
  531. /// <exception cref="T:Renci.SshNet.Common.SshException">A SSH error where <see cref="P:System.Exception.Message" /> is the message from the remote host.</exception>
  532. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  533. /// <remarks>
  534. /// Method calls made by this method to <paramref name="output" />, may under certain conditions result in exceptions thrown by the stream.
  535. /// </remarks>
  536. public IAsyncResult BeginDownloadFile(string path, Stream output, AsyncCallback asyncCallback)
  537. {
  538. return this.BeginDownloadFile(path, output, asyncCallback, null, null);
  539. }
  540. /// <summary>
  541. /// Begins an asynchronous file downloading into the stream.
  542. /// </summary>
  543. /// <param name="path">The path.</param>
  544. /// <param name="output">The output.</param>
  545. /// <param name="asyncCallback">The method to be called when the asynchronous write operation is completed.</param>
  546. /// <param name="state">A user-provided object that distinguishes this particular asynchronous write request from other requests.</param>
  547. /// <param name="downloadCallback">The download callback.</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 whitespace characters.</exception>
  553. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  554. /// <exception cref="Renci.SshNet.Common.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="T:Renci.SshNet.Common.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, AsyncCallback asyncCallback, object state, Action<ulong> downloadCallback = null)
  561. {
  562. CheckDisposed();
  563. if (path.IsNullOrWhiteSpace())
  564. throw new ArgumentException("path");
  565. if (output == null)
  566. throw new ArgumentNullException("output");
  567. var asyncResult = new SftpDownloadAsyncResult(asyncCallback, state);
  568. this.ExecuteThread(() =>
  569. {
  570. try
  571. {
  572. this.InternalDownloadFile(path, output, asyncResult, offset =>
  573. {
  574. asyncResult.Update(offset);
  575. if (downloadCallback != null)
  576. {
  577. downloadCallback(offset);
  578. }
  579. });
  580. asyncResult.SetAsCompleted(null, false);
  581. }
  582. catch (Exception exp)
  583. {
  584. asyncResult.SetAsCompleted(exp, false);
  585. }
  586. });
  587. return asyncResult;
  588. }
  589. /// <summary>
  590. /// Ends an asynchronous file downloading into the stream.
  591. /// </summary>
  592. /// <param name="asyncResult">The pending asynchronous SFTP request.</param>
  593. /// <exception cref="ArgumentException">The IAsyncResult object (<paramref name="asyncResult"/>) did not come from the corresponding async method on this type. <para>-or-</para> EndExecute was called multiple times with the same IAsyncResult.</exception>
  594. public void EndDownloadFile(IAsyncResult asyncResult)
  595. {
  596. var ar = asyncResult as SftpDownloadAsyncResult;
  597. if (ar == null || ar.EndInvokeCalled)
  598. 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.");
  599. // Wait for operation to complete, then return result or throw exception
  600. ar.EndInvoke();
  601. }
  602. /// <summary>
  603. /// Uploads stream into remote file..
  604. /// </summary>
  605. /// <param name="input">Data input stream.</param>
  606. /// <param name="path">Remote file path.</param>
  607. /// <param name="uploadCallback">The upload callback.</param>
  608. /// <exception cref="ArgumentNullException"><paramref name="input" /> is <b>null</b>.</exception>
  609. /// <exception cref="ArgumentException"><paramref name="path" /> is <b>null</b> or contains whitespace characters.</exception>
  610. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  611. /// <exception cref="Renci.SshNet.Common.SftpPermissionDeniedException">Permission to upload the file was denied by the remote host. <para>-or-</para> A SSH command was denied by the server.</exception>
  612. /// <exception cref="T:Renci.SshNet.Common.SshException">A SSH error where <see cref="P:System.Exception.Message" /> is the message from the remote host.</exception>
  613. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  614. /// <remarks>
  615. /// Method calls made by this method to <paramref name="input" />, may under certain conditions result in exceptions thrown by the stream.
  616. /// </remarks>
  617. public void UploadFile(Stream input, string path, Action<ulong> uploadCallback = null)
  618. {
  619. this.UploadFile(input, path, true, uploadCallback);
  620. }
  621. /// <summary>
  622. /// Uploads stream into remote file..
  623. /// </summary>
  624. /// <param name="input">Data input stream.</param>
  625. /// <param name="path">Remote file path.</param>
  626. /// <param name="canOverride">if set to <c>true</c> then existing file will be overwritten.</param>
  627. /// <param name="uploadCallback">The upload callback.</param>
  628. /// <exception cref="ArgumentNullException"><paramref name="input" /> is <b>null</b>.</exception>
  629. /// <exception cref="ArgumentException"><paramref name="path" /> is <b>null</b> or contains whitespace characters.</exception>
  630. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  631. /// <exception cref="Renci.SshNet.Common.SftpPermissionDeniedException">Permission to upload the file was denied by the remote host. <para>-or-</para> A SSH command was denied by the server.</exception>
  632. /// <exception cref="T:Renci.SshNet.Common.SshException">A SSH error where <see cref="P:System.Exception.Message" /> is the message from the remote host.</exception>
  633. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  634. /// <remarks>
  635. /// Method calls made by this method to <paramref name="input" />, may under certain conditions result in exceptions thrown by the stream.
  636. /// </remarks>
  637. public void UploadFile(Stream input, string path, bool canOverride, Action<ulong> uploadCallback = null)
  638. {
  639. CheckDisposed();
  640. var flags = Flags.Write | Flags.Truncate;
  641. if (canOverride)
  642. flags |= Flags.CreateNewOrOpen;
  643. else
  644. flags |= Flags.CreateNew;
  645. this.InternalUploadFile(input, path, flags, null, uploadCallback);
  646. }
  647. /// <summary>
  648. /// Begins an asynchronous uploading the steam into remote file.
  649. /// </summary>
  650. /// <param name="input">Data input stream.</param>
  651. /// <param name="path">Remote file path.</param>
  652. /// <returns>
  653. /// An <see cref="IAsyncResult" /> that references the asynchronous operation.
  654. /// </returns>
  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 whitespace characters.</exception>
  657. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  658. /// <exception cref="Renci.SshNet.Common.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>
  659. /// <exception cref="T:Renci.SshNet.Common.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 IAsyncResult BeginUploadFile(Stream input, string path)
  665. {
  666. return this.BeginUploadFile(input, path, true, null, null, null);
  667. }
  668. /// <summary>
  669. /// Begins an asynchronous uploading the steam into remote file.
  670. /// </summary>
  671. /// <param name="input">Data input stream.</param>
  672. /// <param name="path">Remote file path.</param>
  673. /// <param name="asyncCallback">The method to be called when the asynchronous write operation is completed.</param>
  674. /// <returns>
  675. /// An <see cref="IAsyncResult" /> that references the asynchronous operation.
  676. /// </returns>
  677. /// <exception cref="ArgumentNullException"><paramref name="input" /> is <b>null</b>.</exception>
  678. /// <exception cref="ArgumentException"><paramref name="path" /> is <b>null</b> or contains whitespace characters.</exception>
  679. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  680. /// <exception cref="Renci.SshNet.Common.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>
  681. /// <exception cref="T:Renci.SshNet.Common.SshException">A SSH error where <see cref="P:System.Exception.Message" /> is the message from the remote host.</exception>
  682. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  683. /// <remarks>
  684. /// Method calls made by this method to <paramref name="input" />, may under certain conditions result in exceptions thrown by the stream.
  685. /// </remarks>
  686. public IAsyncResult BeginUploadFile(Stream input, string path, AsyncCallback asyncCallback)
  687. {
  688. return this.BeginUploadFile(input, path, true, asyncCallback, null, null);
  689. }
  690. /// <summary>
  691. /// Begins an asynchronous uploading the steam into remote file.
  692. /// </summary>
  693. /// <param name="input">Data input stream.</param>
  694. /// <param name="path">Remote file path.</param>
  695. /// <param name="asyncCallback">The method to be called when the asynchronous write operation is completed.</param>
  696. /// <param name="state">A user-provided object that distinguishes this particular asynchronous write request from other requests.</param>
  697. /// <param name="uploadCallback">The upload callback.</param>
  698. /// <returns>
  699. /// An <see cref="IAsyncResult" /> that references the asynchronous operation.
  700. /// </returns>
  701. /// <exception cref="ArgumentNullException"><paramref name="input" /> is <b>null</b>.</exception>
  702. /// <exception cref="ArgumentException"><paramref name="path" /> is <b>null</b> or contains whitespace characters.</exception>
  703. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  704. /// <exception cref="Renci.SshNet.Common.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>
  705. /// <exception cref="T:Renci.SshNet.Common.SshException">A SSH error where <see cref="P:System.Exception.Message" /> is the message from the remote host.</exception>
  706. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  707. /// <remarks>
  708. /// Method calls made by this method to <paramref name="input" />, may under certain conditions result in exceptions thrown by the stream.
  709. /// </remarks>
  710. public IAsyncResult BeginUploadFile(Stream input, string path, AsyncCallback asyncCallback, object state, Action<ulong> uploadCallback = null)
  711. {
  712. return this.BeginUploadFile(input, path, true, asyncCallback, state, uploadCallback);
  713. }
  714. /// <summary>
  715. /// Begins an asynchronous uploading the steam into remote file.
  716. /// </summary>
  717. /// <param name="input">Data input stream.</param>
  718. /// <param name="path">Remote file path.</param>
  719. /// <param name="canOverride">if set to <c>true</c> then existing file will be overwritten.</param>
  720. /// <param name="asyncCallback">The method to be called when the asynchronous write operation is completed.</param>
  721. /// <param name="state">A user-provided object that distinguishes this particular asynchronous write request from other requests.</param>
  722. /// <param name="uploadCallback">The upload callback.</param>
  723. /// <returns>
  724. /// An <see cref="IAsyncResult" /> that references the asynchronous operation.
  725. /// </returns>
  726. /// <exception cref="ArgumentNullException"><paramref name="input" /> is <b>null</b>.</exception>
  727. /// <exception cref="ArgumentException"><paramref name="path" /> is <b>null</b> or contains whitespace characters.</exception>
  728. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  729. /// <exception cref="Renci.SshNet.Common.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>
  730. /// <exception cref="T:Renci.SshNet.Common.SshException">A SSH error where <see cref="P:System.Exception.Message" /> is the message from the remote host.</exception>
  731. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  732. /// <remarks>
  733. /// Method calls made by this method to <paramref name="input" />, may under certain conditions result in exceptions thrown by the stream.
  734. /// </remarks>
  735. public IAsyncResult BeginUploadFile(Stream input, string path, bool canOverride, AsyncCallback asyncCallback, object state, Action<ulong> uploadCallback = null)
  736. {
  737. CheckDisposed();
  738. if (input == null)
  739. throw new ArgumentNullException("input");
  740. if (path.IsNullOrWhiteSpace())
  741. throw new ArgumentException("path");
  742. var flags = Flags.Write | Flags.Truncate;
  743. if (canOverride)
  744. flags |= Flags.CreateNewOrOpen;
  745. else
  746. flags |= Flags.CreateNew;
  747. var asyncResult = new SftpUploadAsyncResult(asyncCallback, state);
  748. this.ExecuteThread(() =>
  749. {
  750. try
  751. {
  752. this.InternalUploadFile(input, path, flags, asyncResult, offset =>
  753. {
  754. asyncResult.Update(offset);
  755. if (uploadCallback != null)
  756. {
  757. uploadCallback(offset);
  758. }
  759. });
  760. asyncResult.SetAsCompleted(null, false);
  761. }
  762. catch (Exception exp)
  763. {
  764. asyncResult.SetAsCompleted(exp, false);
  765. }
  766. });
  767. return asyncResult;
  768. }
  769. /// <summary>
  770. /// Ends an asynchronous uploading the steam into remote file.
  771. /// </summary>
  772. /// <param name="asyncResult">The pending asynchronous SFTP request.</param>
  773. /// <exception cref="System.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.</exception>
  774. /// <exception cref="ArgumentException">The IAsyncResult object (<paramref name="asyncResult" />) did not come from the corresponding async method on this type. <para>-or-</para> EndExecute was called multiple times with the same IAsyncResult.</exception>
  775. public void EndUploadFile(IAsyncResult asyncResult)
  776. {
  777. var ar = asyncResult as SftpUploadAsyncResult;
  778. if (ar == null || ar.EndInvokeCalled)
  779. 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.");
  780. // Wait for operation to complete, then return result or throw exception
  781. ar.EndInvoke();
  782. }
  783. /// <summary>
  784. /// Gets status using statvfs@openssh.com request.
  785. /// </summary>
  786. /// <param name="path">The path.</param>
  787. /// <returns>Reference to <see cref="Renci.SshNet.Sftp.SftpFileSytemInformation"/> object that contains file status information.</returns>
  788. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  789. /// <exception cref="ArgumentNullException"><paramref name="path" /> is <b>null</b>.</exception>
  790. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  791. public SftpFileSytemInformation GetStatus(string path)
  792. {
  793. CheckDisposed();
  794. if (path == null)
  795. throw new ArgumentNullException("path");
  796. if (this._sftpSession == null)
  797. throw new SshConnectionException("Client not connected.");
  798. var fullPath = this._sftpSession.GetCanonicalPath(path);
  799. return this._sftpSession.RequestStatVfs(fullPath);
  800. }
  801. #region File Methods
  802. /// <summary>
  803. /// Appends lines to a file, and then closes the file.
  804. /// </summary>
  805. /// <param name="path">The file to append the lines to. The file is created if it does not already exist.</param>
  806. /// <param name="contents">The lines to append to the file.</param>
  807. /// <exception cref="ArgumentNullException"><paramref name="path"/> is<b>null</b> <para>-or-</para> <paramref name="contents"/> is <b>null</b>.</exception>
  808. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  809. public void AppendAllLines(string path, IEnumerable<string> contents)
  810. {
  811. CheckDisposed();
  812. if (contents == null)
  813. throw new ArgumentNullException("contents");
  814. using (var stream = this.AppendText(path))
  815. {
  816. foreach (var line in contents)
  817. {
  818. stream.WriteLine(line);
  819. }
  820. }
  821. }
  822. /// <summary>
  823. /// Appends lines to a file by using a specified encoding, and then closes the file.
  824. /// </summary>
  825. /// <param name="path">The file to append the lines to. The file is created if it does not already exist.</param>
  826. /// <param name="contents">The lines to append to the file.</param>
  827. /// <param name="encoding">The character encoding to use.</param>
  828. /// <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>
  829. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  830. public void AppendAllLines(string path, IEnumerable<string> contents, Encoding encoding)
  831. {
  832. CheckDisposed();
  833. if (contents == null)
  834. throw new ArgumentNullException("contents");
  835. using (var stream = this.AppendText(path, encoding))
  836. {
  837. foreach (var line in contents)
  838. {
  839. stream.WriteLine(line);
  840. }
  841. }
  842. }
  843. /// <summary>
  844. /// Opens a file, appends the specified string to the file, and then closes the file.
  845. /// If the file does not exist, this method creates a file, writes the specified string to the file, then closes the file.
  846. /// </summary>
  847. /// <param name="path">The file to append the specified string to.</param>
  848. /// <param name="contents">The string to append to the file.</param>
  849. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>. <para>-or-</para> <paramref name="contents"/> is <b>null</b>.</exception>
  850. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  851. public void AppendAllText(string path, string contents)
  852. {
  853. using (var stream = this.AppendText(path))
  854. {
  855. stream.Write(contents);
  856. }
  857. }
  858. /// <summary>
  859. /// Opens a file, appends the specified string to the file, and then closes the file.
  860. /// If the file does not exist, this method creates a file, writes the specified string to the file, then closes the file.
  861. /// </summary>
  862. /// <param name="path">The file to append the specified string to.</param>
  863. /// <param name="contents">The string to append to the file.</param>
  864. /// <param name="encoding">The character encoding to use.</param>
  865. /// <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>
  866. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  867. public void AppendAllText(string path, string contents, Encoding encoding)
  868. {
  869. using (var stream = this.AppendText(path, encoding))
  870. {
  871. stream.Write(contents);
  872. }
  873. }
  874. /// <summary>
  875. /// Creates a <see cref="System.IO.StreamWriter"/> that appends UTF-8 encoded text to an existing file.
  876. /// </summary>
  877. /// <param name="path">The path to the file to append to.</param>
  878. /// <returns>A StreamWriter that appends UTF-8 encoded text to an existing file.</returns>
  879. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  880. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  881. public StreamWriter AppendText(string path)
  882. {
  883. return this.AppendText(path, Encoding.UTF8);
  884. }
  885. /// <summary>
  886. /// Creates a <see cref="System.IO.StreamWriter"/> that appends UTF-8 encoded text to an existing file.
  887. /// </summary>
  888. /// <param name="path">The path to the file to append to.</param>
  889. /// <param name="encoding">The character encoding to use.</param>
  890. /// <returns>
  891. /// A StreamWriter that appends UTF-8 encoded text to an existing file.
  892. /// </returns>
  893. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>. <para>-or-</para> <paramref name="encoding"/> is <b>null</b>.</exception>
  894. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  895. public StreamWriter AppendText(string path, Encoding encoding)
  896. {
  897. CheckDisposed();
  898. if (encoding == null)
  899. throw new ArgumentNullException("encoding");
  900. return new StreamWriter(new SftpFileStream(this._sftpSession, path, FileMode.Append, FileAccess.Write), encoding);
  901. }
  902. /// <summary>
  903. /// Creates or overwrites a file in the specified path.
  904. /// </summary>
  905. /// <param name="path">The path and name of the file to create.</param>
  906. /// <returns>A <see cref="SftpFileStream"/> that provides read/write access to the file specified in path</returns>
  907. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  908. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  909. public SftpFileStream Create(string path)
  910. {
  911. CheckDisposed();
  912. return new SftpFileStream(this._sftpSession, path, FileMode.Create, FileAccess.ReadWrite);
  913. }
  914. /// <summary>
  915. /// Creates or overwrites the specified file.
  916. /// </summary>
  917. /// <param name="path">The path and name of the file to create.</param>
  918. /// <param name="bufferSize">The number of bytes buffered for reads and writes to the file.</param>
  919. /// <returns>A <see cref="SftpFileStream"/> that provides read/write access to the file specified in path</returns>
  920. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  921. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  922. public SftpFileStream Create(string path, int bufferSize)
  923. {
  924. CheckDisposed();
  925. return new SftpFileStream(this._sftpSession, path, FileMode.Create, FileAccess.ReadWrite, bufferSize);
  926. }
  927. /// <summary>
  928. /// Creates or opens a file for writing UTF-8 encoded text.
  929. /// </summary>
  930. /// <param name="path">The file to be opened for writing.</param>
  931. /// <returns>A <see cref="System.IO.StreamWriter"/> that writes to the specified file using UTF-8 encoding.</returns>
  932. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  933. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  934. public StreamWriter CreateText(string path)
  935. {
  936. return CreateText(path, Encoding.UTF8);
  937. }
  938. /// <summary>
  939. /// Creates or opens a file for writing UTF-8 encoded text.
  940. /// </summary>
  941. /// <param name="path">The file to be opened for writing.</param>
  942. /// <param name="encoding">The character encoding to use.</param>
  943. /// <returns> A <see cref="System.IO.StreamWriter"/> that writes to the specified file using UTF-8 encoding. </returns>
  944. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  945. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  946. public StreamWriter CreateText(string path, Encoding encoding)
  947. {
  948. CheckDisposed();
  949. return new StreamWriter(this.OpenWrite(path), encoding);
  950. }
  951. /// <summary>
  952. /// Deletes the specified file or directory. An exception is not thrown if the specified file does not exist.
  953. /// </summary>
  954. /// <param name="path">The name of the file or directory to be deleted. Wildcard characters are not supported.</param>
  955. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  956. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  957. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  958. public void Delete(string path)
  959. {
  960. var file = this.Get(path);
  961. file.Delete();
  962. }
  963. /// <summary>
  964. /// Returns the date and time the specified file or directory was last accessed.
  965. /// </summary>
  966. /// <param name="path">The file or directory for which to obtain access date and time information.</param>
  967. /// <returns>A <see cref="System.DateTime"/> structure set to the date and time that the specified file or directory was last accessed. This value is expressed in local time.</returns>
  968. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  969. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  970. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  971. public DateTime GetLastAccessTime(string path)
  972. {
  973. var file = this.Get(path);
  974. return file.LastAccessTime;
  975. }
  976. /// <summary>
  977. /// Returns the date and time, in coordinated universal time (UTC), that the specified file or directory was last accessed.
  978. /// </summary>
  979. /// <param name="path">The file or directory for which to obtain access date and time information.</param>
  980. /// <returns>A <see cref="System.DateTime"/> structure set to the date and time that the specified file or directory was last accessed. This value is expressed in UTC time.</returns>
  981. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  982. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  983. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  984. public DateTime GetLastAccessTimeUtc(string path)
  985. {
  986. var lastAccessTime = GetLastAccessTime(path);
  987. return lastAccessTime.ToUniversalTime();
  988. }
  989. /// <summary>
  990. /// Returns the date and time the specified file or directory was last written to.
  991. /// </summary>
  992. /// <param name="path">The file or directory for which to obtain write date and time information.</param>
  993. /// <returns>A <see cref="System.DateTime"/> structure set to the date and time that the specified file or directory was last written to. This value is expressed in local time.</returns>
  994. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  995. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  996. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  997. public DateTime GetLastWriteTime(string path)
  998. {
  999. var file = this.Get(path);
  1000. return file.LastWriteTime;
  1001. }
  1002. /// <summary>
  1003. /// Returns the date and time, in coordinated universal time (UTC), that the specified file or directory was last written to.
  1004. /// </summary>
  1005. /// <param name="path">The file or directory for which to obtain write date and time information.</param>
  1006. /// <returns>A <see cref="System.DateTime"/> structure set to the date and time that the specified file or directory was last written to. This value is expressed in UTC time.</returns>
  1007. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  1008. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  1009. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1010. public DateTime GetLastWriteTimeUtc(string path)
  1011. {
  1012. var lastWriteTime = GetLastWriteTime(path);
  1013. return lastWriteTime.ToUniversalTime();
  1014. }
  1015. /// <summary>
  1016. /// Opens a <see cref="SftpFileStream"/> on the specified path with read/write access.
  1017. /// </summary>
  1018. /// <param name="path">The file to open.</param>
  1019. /// <param name="mode">A <see cref="System.IO.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>
  1020. /// <returns>An unshared <see cref="SftpFileStream"/> that provides access to the specified file, with the specified mode and access.</returns>
  1021. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  1022. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1023. public SftpFileStream Open(string path, FileMode mode)
  1024. {
  1025. return Open(path, mode, FileAccess.ReadWrite);
  1026. }
  1027. /// <summary>
  1028. /// Opens a <see cref="SftpFileStream"/> on the specified path, with the specified mode and access.
  1029. /// </summary>
  1030. /// <param name="path">The file to open.</param>
  1031. /// <param name="mode">A <see cref="System.IO.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>
  1032. /// <param name="access">A <see cref="System.IO.FileAccess"/> value that specifies the operations that can be performed on the file.</param>
  1033. /// <returns>An unshared <see cref="SftpFileStream"/> that provides access to the specified file, with the specified mode and access.</returns>
  1034. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  1035. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1036. public SftpFileStream Open(string path, FileMode mode, FileAccess access)
  1037. {
  1038. CheckDisposed();
  1039. return new SftpFileStream(this._sftpSession, path, mode, access, (int) _bufferSize);
  1040. }
  1041. /// <summary>
  1042. /// Opens an existing file for reading.
  1043. /// </summary>
  1044. /// <param name="path">The file to be opened for reading.</param>
  1045. /// <returns>A read-only System.IO.FileStream on the specified path.</returns>
  1046. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  1047. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1048. public SftpFileStream OpenRead(string path)
  1049. {
  1050. return Open(path, FileMode.Open, FileAccess.Read);
  1051. }
  1052. /// <summary>
  1053. /// Opens an existing UTF-8 encoded text file for reading.
  1054. /// </summary>
  1055. /// <param name="path">The file to be opened for reading.</param>
  1056. /// <returns>A <see cref="System.IO.StreamReader"/> on the specified path.</returns>
  1057. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  1058. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1059. public StreamReader OpenText(string path)
  1060. {
  1061. return new StreamReader(this.OpenRead(path), Encoding.UTF8);
  1062. }
  1063. /// <summary>
  1064. /// Opens an existing file for writing.
  1065. /// </summary>
  1066. /// <param name="path">The file to be opened for writing.</param>
  1067. /// <returns>An unshared <see cref="SftpFileStream"/> object on the specified path with <see cref="System.IO.FileAccess.Write"/> access.</returns>
  1068. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  1069. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1070. public SftpFileStream OpenWrite(string path)
  1071. {
  1072. CheckDisposed();
  1073. return new SftpFileStream(this._sftpSession, path, FileMode.OpenOrCreate, FileAccess.Write,
  1074. (int) _bufferSize);
  1075. }
  1076. /// <summary>
  1077. /// Opens a binary file, reads the contents of the file into a byte array, and then closes the file.
  1078. /// </summary>
  1079. /// <param name="path">The file to open for reading.</param>
  1080. /// <returns>A byte array containing the contents of the file.</returns>
  1081. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  1082. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1083. public byte[] ReadAllBytes(string path)
  1084. {
  1085. using (var stream = this.OpenRead(path))
  1086. {
  1087. var buffer = new byte[stream.Length];
  1088. stream.Read(buffer, 0, buffer.Length);
  1089. return buffer;
  1090. }
  1091. }
  1092. /// <summary>
  1093. /// Opens a text file, reads all lines of the file, and then closes the file.
  1094. /// </summary>
  1095. /// <param name="path">The file to open for reading.</param>
  1096. /// <returns>A string array containing all lines of the file.</returns>
  1097. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  1098. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1099. public string[] ReadAllLines(string path)
  1100. {
  1101. return this.ReadAllLines(path, Encoding.UTF8);
  1102. }
  1103. /// <summary>
  1104. /// Opens a file, reads all lines of the file with the specified encoding, and then closes the file.
  1105. /// </summary>
  1106. /// <param name="path">The file to open for reading.</param>
  1107. /// <param name="encoding">The encoding applied to the contents of the file.</param>
  1108. /// <returns>A string array containing all lines of the file.</returns>
  1109. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  1110. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1111. public string[] ReadAllLines(string path, Encoding encoding)
  1112. {
  1113. var lines = new List<string>();
  1114. using (var stream = new StreamReader(this.OpenRead(path), encoding))
  1115. {
  1116. while (!stream.EndOfStream)
  1117. {
  1118. lines.Add(stream.ReadLine());
  1119. }
  1120. }
  1121. return lines.ToArray();
  1122. }
  1123. /// <summary>
  1124. /// Opens a text file, reads all lines of the file, and then closes the file.
  1125. /// </summary>
  1126. /// <param name="path">The file to open for reading.</param>
  1127. /// <returns>A string containing all lines of the file.</returns>
  1128. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  1129. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1130. public string ReadAllText(string path)
  1131. {
  1132. return this.ReadAllText(path, Encoding.UTF8);
  1133. }
  1134. /// <summary>
  1135. /// Opens a file, reads all lines of the file with the specified encoding, and then closes the file.
  1136. /// </summary>
  1137. /// <param name="path">The file to open for reading.</param>
  1138. /// <param name="encoding">The encoding applied to the contents of the file.</param>
  1139. /// <returns>A string containing all lines of the file.</returns>
  1140. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  1141. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1142. public string ReadAllText(string path, Encoding encoding)
  1143. {
  1144. using (var stream = new StreamReader(this.OpenRead(path), encoding))
  1145. {
  1146. return stream.ReadToEnd();
  1147. }
  1148. }
  1149. /// <summary>
  1150. /// Reads the lines of a file.
  1151. /// </summary>
  1152. /// <param name="path">The file to read.</param>
  1153. /// <returns>The lines of the file.</returns>
  1154. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  1155. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1156. public IEnumerable<string> ReadLines(string path)
  1157. {
  1158. return this.ReadAllLines(path);
  1159. }
  1160. /// <summary>
  1161. /// Read the lines of a file that has a specified encoding.
  1162. /// </summary>
  1163. /// <param name="path">The file to read.</param>
  1164. /// <param name="encoding">The encoding that is applied to the contents of the file.</param>
  1165. /// <returns>The lines of the file.</returns>
  1166. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  1167. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1168. public IEnumerable<string> ReadLines(string path, Encoding encoding)
  1169. {
  1170. return this.ReadAllLines(path, encoding);
  1171. }
  1172. /// <summary>
  1173. /// Sets the date and time the specified file was last accessed.
  1174. /// </summary>
  1175. /// <param name="path">The file for which to set the access date and time information.</param>
  1176. /// <param name="lastAccessTime">A <see cref="System.DateTime"/> containing the value to set for the last access date and time of path. This value is expressed in local time.</param>
  1177. [Obsolete("Note: This method currently throws NotImplementedException because it has not yet been implemented.")]
  1178. public void SetLastAccessTime(string path, DateTime lastAccessTime)
  1179. {
  1180. throw new NotImplementedException();
  1181. }
  1182. /// <summary>
  1183. /// Sets the date and time, in coordinated universal time (UTC), that the specified file was last accessed.
  1184. /// </summary>
  1185. /// <param name="path">The file for which to set the access date and time information.</param>
  1186. /// <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>
  1187. [Obsolete("Note: This method currently throws NotImplementedException because it has not yet been implemented.")]
  1188. public void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc)
  1189. {
  1190. throw new NotImplementedException();
  1191. }
  1192. /// <summary>
  1193. /// Sets the date and time that the specified file was last written to.
  1194. /// </summary>
  1195. /// <param name="path">The file for which to set the date and time information.</param>
  1196. /// <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>
  1197. [Obsolete("Note: This method currently throws NotImplementedException because it has not yet been implemented.")]
  1198. public void SetLastWriteTime(string path, DateTime lastWriteTime)
  1199. {
  1200. throw new NotImplementedException();
  1201. }
  1202. /// <summary>
  1203. /// Sets the date and time, in coordinated universal time (UTC), that the specified file was last written to.
  1204. /// </summary>
  1205. /// <param name="path">The file for which to set the date and time information.</param>
  1206. /// <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>
  1207. [Obsolete("Note: This method currently throws NotImplementedException because it has not yet been implemented.")]
  1208. public void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc)
  1209. {
  1210. throw new NotImplementedException();
  1211. }
  1212. /// <summary>
  1213. /// Creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten.
  1214. /// </summary>
  1215. /// <param name="path">The file to write to.</param>
  1216. /// <param name="bytes">The bytes to write to the file.</param>
  1217. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  1218. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1219. public void WriteAllBytes(string path, byte[] bytes)
  1220. {
  1221. using (var stream = this.OpenWrite(path))
  1222. {
  1223. stream.Write(bytes, 0, bytes.Length);
  1224. }
  1225. }
  1226. /// <summary>
  1227. /// Creates a new file, writes a collection of strings to the file, and then closes the file.
  1228. /// </summary>
  1229. /// <param name="path">The file to write to.</param>
  1230. /// <param name="contents">The lines to write to the file.</param>
  1231. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  1232. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1233. public void WriteAllLines(string path, IEnumerable<string> contents)
  1234. {
  1235. this.WriteAllLines(path, contents, Encoding.UTF8);
  1236. }
  1237. /// <summary>
  1238. /// Creates a new file, write the specified string array to the file, and then closes the file.
  1239. /// </summary>
  1240. /// <param name="path">The file to write to.</param>
  1241. /// <param name="contents">The string array to write to the file.</param>
  1242. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  1243. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1244. public void WriteAllLines(string path, string[] contents)
  1245. {
  1246. this.WriteAllLines(path, contents, Encoding.UTF8);
  1247. }
  1248. /// <summary>
  1249. /// Creates a new file by using the specified encoding, writes a collection of strings to the file, and then closes the file.
  1250. /// </summary>
  1251. /// <param name="path">The file to write to.</param>
  1252. /// <param name="contents">The lines to write to the file.</param>
  1253. /// <param name="encoding">The character encoding to use.</param>
  1254. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  1255. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1256. public void WriteAllLines(string path, IEnumerable<string> contents, Encoding encoding)
  1257. {
  1258. using (var stream = this.CreateText(path, encoding))
  1259. {
  1260. foreach (var line in contents)
  1261. {
  1262. stream.WriteLine(line);
  1263. }
  1264. }
  1265. }
  1266. /// <summary>
  1267. /// Creates a new file, writes the specified string array to the file by using the specified encoding, and then closes the file.
  1268. /// </summary>
  1269. /// <param name="path">The file to write to.</param>
  1270. /// <param name="contents">The string array to write to the file.</param>
  1271. /// <param name="encoding">An <see cref="System.Text.Encoding"/> object that represents the character encoding applied to the string array.</param>
  1272. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  1273. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1274. public void WriteAllLines(string path, string[] contents, Encoding encoding)
  1275. {
  1276. using (var stream = this.CreateText(path, encoding))
  1277. {
  1278. foreach (var line in contents)
  1279. {
  1280. stream.WriteLine(line);
  1281. }
  1282. }
  1283. }
  1284. /// <summary>
  1285. /// Creates a new file, writes the specified string to the file, and then closes the file. If the target file already exists, it is overwritten.
  1286. /// </summary>
  1287. /// <param name="path">The file to write to.</param>
  1288. /// <param name="contents">The string to write to the file.</param>
  1289. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  1290. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1291. public void WriteAllText(string path, string contents)
  1292. {
  1293. using (var stream = this.CreateText(path))
  1294. {
  1295. stream.Write(contents);
  1296. }
  1297. }
  1298. /// <summary>
  1299. /// Creates a new file, writes the specified string to the file using the specified encoding, and then closes the file. If the target file already exists, it is overwritten.
  1300. /// </summary>
  1301. /// <param name="path">The file to write to.</param>
  1302. /// <param name="contents">The string to write to the file.</param>
  1303. /// <param name="encoding">The encoding to apply to the string.</param>
  1304. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  1305. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1306. public void WriteAllText(string path, string contents, Encoding encoding)
  1307. {
  1308. using (var stream = this.CreateText(path, encoding))
  1309. {
  1310. stream.Write(contents);
  1311. }
  1312. }
  1313. /// <summary>
  1314. /// Gets the <see cref="SftpFileAttributes"/> of the file on the path.
  1315. /// </summary>
  1316. /// <param name="path">The path to the file.</param>
  1317. /// <returns>The <see cref="SftpFileAttributes"/> of the file on the path.</returns>
  1318. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  1319. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1320. public SftpFileAttributes GetAttributes(string path)
  1321. {
  1322. CheckDisposed();
  1323. if (this._sftpSession == null)
  1324. throw new SshConnectionException("Client not connected.");
  1325. var fullPath = this._sftpSession.GetCanonicalPath(path);
  1326. return this._sftpSession.RequestLStat(fullPath);
  1327. }
  1328. /// <summary>
  1329. /// Sets the specified <see cref="SftpFileAttributes"/> of the file on the specified path.
  1330. /// </summary>
  1331. /// <param name="path">The path to the file.</param>
  1332. /// <param name="fileAttributes">The desired <see cref="SftpFileAttributes"/>.</param>
  1333. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  1334. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1335. public void SetAttributes(string path, SftpFileAttributes fileAttributes)
  1336. {
  1337. CheckDisposed();
  1338. if (this._sftpSession == null)
  1339. throw new SshConnectionException("Client not connected.");
  1340. var fullPath = this._sftpSession.GetCanonicalPath(path);
  1341. this._sftpSession.RequestSetStat(fullPath, fileAttributes);
  1342. }
  1343. // Please don't forget this when you implement these methods: <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception>
  1344. //public FileSecurity GetAccessControl(string path);
  1345. //public FileSecurity GetAccessControl(string path, AccessControlSections includeSections);
  1346. //public DateTime GetCreationTime(string path);
  1347. //public DateTime GetCreationTimeUtc(string path);
  1348. //public void SetAccessControl(string path, FileSecurity fileSecurity);
  1349. //public void SetCreationTime(string path, DateTime creationTime);
  1350. //public void SetCreationTimeUtc(string path, DateTime creationTimeUtc);
  1351. #endregion
  1352. /// <summary>
  1353. /// Internals the list directory.
  1354. /// </summary>
  1355. /// <param name="path">The path.</param>
  1356. /// <param name="listCallback">The list callback.</param>
  1357. /// <returns></returns>
  1358. /// <exception cref="System.ArgumentNullException">path</exception>
  1359. /// <exception cref="ArgumentNullException"><paramref name="path" /> is <b>null</b>.</exception>
  1360. /// <exception cref="SshConnectionException">Client not connected.</exception>
  1361. private IEnumerable<SftpFile> InternalListDirectory(string path, Action<int> listCallback)
  1362. {
  1363. if (path == null)
  1364. throw new ArgumentNullException("path");
  1365. if (this._sftpSession == null)
  1366. throw new SshConnectionException("Client not connected.");
  1367. var fullPath = this._sftpSession.GetCanonicalPath(path);
  1368. var handle = this._sftpSession.RequestOpenDir(fullPath);
  1369. var basePath = fullPath;
  1370. if (!basePath.EndsWith("/"))
  1371. basePath = string.Format("{0}/", fullPath);
  1372. var result = new List<SftpFile>();
  1373. var files = this._sftpSession.RequestReadDir(handle);
  1374. while (files != null)
  1375. {
  1376. result.AddRange(from f in files
  1377. select new SftpFile(this._sftpSession, string.Format(CultureInfo.InvariantCulture, "{0}{1}", basePath, f.Key), f.Value));
  1378. // Call callback to report number of files read
  1379. if (listCallback != null)
  1380. {
  1381. // Execute callback on different thread
  1382. this.ExecuteThread(() => listCallback(result.Count));
  1383. }
  1384. files = this._sftpSession.RequestReadDir(handle);
  1385. }
  1386. this._sftpSession.RequestClose(handle);
  1387. return result;
  1388. }
  1389. /// <summary>
  1390. /// Internals the download file.
  1391. /// </summary>
  1392. /// <param name="path">The path.</param>
  1393. /// <param name="output">The output.</param>
  1394. /// <param name="asyncResult">An <see cref="IAsyncResult"/> that references the asynchronous request.</param>
  1395. /// <param name="downloadCallback">The download callback.</param>
  1396. /// <exception cref="ArgumentNullException"><paramref name="output" /> is <b>null</b>.</exception>
  1397. /// <exception cref="ArgumentException"><paramref name="path" /> is <b>null</b> or contains whitespace.</exception>
  1398. /// <exception cref="SshConnectionException">Client not connected.</exception>
  1399. private void InternalDownloadFile(string path, Stream output, SftpDownloadAsyncResult asyncResult, Action<ulong> downloadCallback)
  1400. {
  1401. if (output == null)
  1402. throw new ArgumentNullException("output");
  1403. if (path.IsNullOrWhiteSpace())
  1404. throw new ArgumentException("path");
  1405. if (this._sftpSession == null)
  1406. throw new SshConnectionException("Client not connected.");
  1407. var fullPath = this._sftpSession.GetCanonicalPath(path);
  1408. var handle = this._sftpSession.RequestOpen(fullPath, Flags.Read);
  1409. ulong offset = 0;
  1410. var optimalReadLength = _sftpSession.CalculateOptimalReadLength(_bufferSize);
  1411. var data = this._sftpSession.RequestRead(handle, offset, optimalReadLength);
  1412. // Read data while available
  1413. while (data.Length > 0)
  1414. {
  1415. // Cancel download
  1416. if (asyncResult != null && asyncResult.IsDownloadCanceled)
  1417. break;
  1418. output.Write(data, 0, data.Length);
  1419. output.Flush();
  1420. offset += (ulong)data.Length;
  1421. // Call callback to report number of bytes read
  1422. if (downloadCallback != null)
  1423. {
  1424. // Execute callback on different thread
  1425. this.ExecuteThread(() => { downloadCallback(offset); });
  1426. }
  1427. data = this._sftpSession.RequestRead(handle, offset, optimalReadLength);
  1428. }
  1429. this._sftpSession.RequestClose(handle);
  1430. }
  1431. /// <summary>
  1432. /// Internals the upload file.
  1433. /// </summary>
  1434. /// <param name="input">The input.</param>
  1435. /// <param name="path">The path.</param>
  1436. /// <param name="flags">The flags.</param>
  1437. /// <param name="asyncResult">An <see cref="IAsyncResult"/> that references the asynchronous request.</param>
  1438. /// <param name="uploadCallback">The upload callback.</param>
  1439. /// <exception cref="ArgumentNullException"><paramref name="input" /> is <b>null</b>.</exception>
  1440. /// <exception cref="ArgumentException"><paramref name="path" /> is <b>null</b> or contains whitespace.</exception>
  1441. /// <exception cref="SshConnectionException">Client not connected.</exception>
  1442. private void InternalUploadFile(Stream input, string path, Flags flags, SftpUploadAsyncResult asyncResult, Action<ulong> uploadCallback)
  1443. {
  1444. if (input == null)
  1445. throw new ArgumentNullException("input");
  1446. if (path.IsNullOrWhiteSpace())
  1447. throw new ArgumentException("path");
  1448. if (this._sftpSession == null)
  1449. throw new SshConnectionException("Client not connected.");
  1450. var fullPath = this._sftpSession.GetCanonicalPath(path);
  1451. var handle = this._sftpSession.RequestOpen(fullPath, flags);
  1452. ulong offset = 0;
  1453. // create buffer of optimal length
  1454. var buffer = new byte[_sftpSession.CalculateOptimalWriteLength(_bufferSize, handle)];
  1455. var bytesRead = input.Read(buffer, 0, buffer.Length);
  1456. var expectedResponses = 0;
  1457. var responseReceivedWaitHandle = new AutoResetEvent(false);
  1458. do
  1459. {
  1460. // Cancel upload
  1461. if (asyncResult != null && asyncResult.IsUploadCanceled)
  1462. break;
  1463. if (bytesRead > 0)
  1464. {
  1465. if (bytesRead < buffer.Length)
  1466. {
  1467. // Replace buffer for last chunk of data
  1468. var data = new byte[bytesRead];
  1469. Buffer.BlockCopy(buffer, 0, data, 0, bytesRead);
  1470. buffer = data;
  1471. }
  1472. var writtenBytes = offset + (ulong)buffer.Length;
  1473. this._sftpSession.RequestWrite(handle, offset, buffer, null, s =>
  1474. {
  1475. if (s.StatusCode == StatusCodes.Ok)
  1476. {
  1477. Interlocked.Decrement(ref expectedResponses);
  1478. responseReceivedWaitHandle.Set();
  1479. // Call callback to report number of bytes written
  1480. if (uploadCallback != null)
  1481. {
  1482. // Execute callback on different thread
  1483. this.ExecuteThread(() => uploadCallback(writtenBytes));
  1484. }
  1485. }
  1486. });
  1487. Interlocked.Increment(ref expectedResponses);
  1488. offset += (uint)bytesRead;
  1489. bytesRead = input.Read(buffer, 0, buffer.Length);
  1490. }
  1491. else if (expectedResponses > 0)
  1492. {
  1493. // Wait for expectedResponses to change
  1494. this._sftpSession.WaitOnHandle(responseReceivedWaitHandle, this.OperationTimeout);
  1495. }
  1496. } while (expectedResponses > 0 || bytesRead > 0);
  1497. this._sftpSession.RequestClose(handle);
  1498. }
  1499. partial void ExecuteThread(Action action);
  1500. /// <summary>
  1501. /// Called when client is connected to the server.
  1502. /// </summary>
  1503. protected override void OnConnected()
  1504. {
  1505. base.OnConnected();
  1506. this._sftpSession = new SftpSession(this.Session, this.OperationTimeout, this.ConnectionInfo.Encoding);
  1507. this._sftpSession.Connect();
  1508. }
  1509. /// <summary>
  1510. /// Called when client is disconnecting from the server.
  1511. /// </summary>
  1512. protected override void OnDisconnecting()
  1513. {
  1514. base.OnDisconnecting();
  1515. // disconnect and dispose the SFTP session
  1516. // the dispose is necessary since we create a new SFTP session
  1517. // on each connect
  1518. if (_sftpSession != null)
  1519. {
  1520. this._sftpSession.Disconnect();
  1521. this._sftpSession.Dispose();
  1522. this._sftpSession = null;
  1523. }
  1524. }
  1525. /// <summary>
  1526. /// Releases unmanaged and - optionally - managed resources
  1527. /// </summary>
  1528. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged ResourceMessages.</param>
  1529. protected override void Dispose(bool disposing)
  1530. {
  1531. if (this._sftpSession != null)
  1532. {
  1533. this._sftpSession.Dispose();
  1534. this._sftpSession = null;
  1535. }
  1536. base.Dispose(disposing);
  1537. }
  1538. }
  1539. }