SftpClient.cs 94 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787
  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="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="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="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="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="SftpPathNotFoundException"><paramref name="path"/> does not exist.</exception>
  265. /// <exception cref="SftpPermissionDeniedException">Permission to delete the directory was denied by the remote host. <para>-or-</para> A SSH command was denied by the server.</exception>
  266. /// <exception cref="SshException">A SSH error where <see cref="P:System.Exception.Message"/> is the message from the remote host.</exception>
  267. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  268. public void DeleteDirectory(string path)
  269. {
  270. CheckDisposed();
  271. if (path.IsNullOrWhiteSpace())
  272. throw new ArgumentException("path");
  273. if (this._sftpSession == null)
  274. throw new SshConnectionException("Client not connected.");
  275. var fullPath = this._sftpSession.GetCanonicalPath(path);
  276. this._sftpSession.RequestRmDir(fullPath);
  277. }
  278. /// <summary>
  279. /// Deletes remote file specified by path.
  280. /// </summary>
  281. /// <param name="path">File to be deleted path.</param>
  282. /// <exception cref="ArgumentException"><paramref name="path"/> is <b>null</b> or contains whitespace characters.</exception>
  283. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  284. /// <exception cref="SftpPathNotFoundException"><paramref name="path"/> does not exist.</exception>
  285. /// <exception cref="SftpPermissionDeniedException">Permission to delete the file was denied by the remote host. <para>-or-</para> A SSH command was denied by the server.</exception>
  286. /// <exception cref="SshException">A SSH error where <see cref="P:System.Exception.Message"/> is the message from the remote host.</exception>
  287. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  288. public void DeleteFile(string path)
  289. {
  290. CheckDisposed();
  291. if (path.IsNullOrWhiteSpace())
  292. throw new ArgumentException("path");
  293. if (this._sftpSession == null)
  294. throw new SshConnectionException("Client not connected.");
  295. var fullPath = this._sftpSession.GetCanonicalPath(path);
  296. this._sftpSession.RequestRemove(fullPath);
  297. }
  298. /// <summary>
  299. /// Renames remote file from old path to new path.
  300. /// </summary>
  301. /// <param name="oldPath">Path to the old file location.</param>
  302. /// <param name="newPath">Path to the new file location.</param>
  303. /// <exception cref="ArgumentNullException"><paramref name="oldPath"/> is <b>null</b>. <para>-or-</para> or <paramref name="newPath"/> is <b>null</b>.</exception>
  304. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  305. /// <exception cref="SftpPermissionDeniedException">Permission to rename the file was denied by the remote host. <para>-or-</para> A SSH command was denied by the server.</exception>
  306. /// <exception cref="SshException">A SSH error where <see cref="P:System.Exception.Message"/> is the message from the remote host.</exception>
  307. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  308. public void RenameFile(string oldPath, string newPath)
  309. {
  310. this.RenameFile(oldPath, newPath, false);
  311. }
  312. /// <summary>
  313. /// Renames remote file from old path to new path.
  314. /// </summary>
  315. /// <param name="oldPath">Path to the old file location.</param>
  316. /// <param name="newPath">Path to the new file location.</param>
  317. /// <param name="isPosix">if set to <c>true</c> then perform a posix rename.</param>
  318. /// <exception cref="ArgumentNullException"><paramref name="oldPath" /> is <b>null</b>. <para>-or-</para> or <paramref name="newPath" /> is <b>null</b>.</exception>
  319. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  320. /// <exception cref="SftpPermissionDeniedException">Permission to rename the file was denied by the remote host. <para>-or-</para> A SSH command was denied by the server.</exception>
  321. /// <exception cref="SshException">A SSH error where <see cref="P:System.Exception.Message" /> is the message from the remote host.</exception>
  322. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  323. public void RenameFile(string oldPath, string newPath, bool isPosix)
  324. {
  325. CheckDisposed();
  326. if (oldPath == null)
  327. throw new ArgumentNullException("oldPath");
  328. if (newPath == null)
  329. throw new ArgumentNullException("newPath");
  330. if (this._sftpSession == null)
  331. throw new SshConnectionException("Client not connected.");
  332. var oldFullPath = this._sftpSession.GetCanonicalPath(oldPath);
  333. var newFullPath = this._sftpSession.GetCanonicalPath(newPath);
  334. if (isPosix)
  335. {
  336. this._sftpSession.RequestPosixRename(oldFullPath, newFullPath);
  337. }
  338. else
  339. {
  340. this._sftpSession.RequestRename(oldFullPath, newFullPath);
  341. }
  342. }
  343. /// <summary>
  344. /// Creates a symbolic link from old path to new path.
  345. /// </summary>
  346. /// <param name="path">The old path.</param>
  347. /// <param name="linkPath">The new path.</param>
  348. /// <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>
  349. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  350. /// <exception cref="SftpPermissionDeniedException">Permission to create the symbolic link was denied by the remote host. <para>-or-</para> A SSH command was denied by the server.</exception>
  351. /// <exception cref="SshException">A SSH error where <see cref="P:System.Exception.Message"/> is the message from the remote host.</exception>
  352. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  353. public void SymbolicLink(string path, string linkPath)
  354. {
  355. CheckDisposed();
  356. if (path.IsNullOrWhiteSpace())
  357. throw new ArgumentException("path");
  358. if (linkPath.IsNullOrWhiteSpace())
  359. throw new ArgumentException("linkPath");
  360. if (this._sftpSession == null)
  361. throw new SshConnectionException("Client not connected.");
  362. var fullPath = this._sftpSession.GetCanonicalPath(path);
  363. var linkFullPath = this._sftpSession.GetCanonicalPath(linkPath);
  364. this._sftpSession.RequestSymLink(fullPath, linkFullPath);
  365. }
  366. /// <summary>
  367. /// Retrieves list of files in remote directory.
  368. /// </summary>
  369. /// <param name="path">The path.</param>
  370. /// <param name="listCallback">The list callback.</param>
  371. /// <returns>
  372. /// List of directory entries
  373. /// </returns>
  374. /// <exception cref="ArgumentNullException"><paramref name="path" /> is <b>null</b>.</exception>
  375. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  376. /// <exception cref="SftpPermissionDeniedException">Permission to list the contents of the directory was denied by the remote host. <para>-or-</para> A SSH command was denied by the server.</exception>
  377. /// <exception cref="SshException">A SSH error where <see cref="P:System.Exception.Message" /> is the message from the remote host.</exception>
  378. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  379. public IEnumerable<SftpFile> ListDirectory(string path, Action<int> listCallback = null)
  380. {
  381. CheckDisposed();
  382. return InternalListDirectory(path, listCallback);
  383. }
  384. /// <summary>
  385. /// Begins an asynchronous operation of retrieving list of files in remote directory.
  386. /// </summary>
  387. /// <param name="path">The path.</param>
  388. /// <param name="asyncCallback">The method to be called when the asynchronous write operation is completed.</param>
  389. /// <param name="state">A user-provided object that distinguishes this particular asynchronous write request from other requests.</param>
  390. /// <param name="listCallback">The list callback.</param>
  391. /// <returns>
  392. /// An <see cref="IAsyncResult" /> that references the asynchronous operation.
  393. /// </returns>
  394. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  395. public IAsyncResult BeginListDirectory(string path, AsyncCallback asyncCallback, object state, Action<int> listCallback = null)
  396. {
  397. CheckDisposed();
  398. var asyncResult = new SftpListDirectoryAsyncResult(asyncCallback, state);
  399. this.ExecuteThread(() =>
  400. {
  401. try
  402. {
  403. var result = this.InternalListDirectory(path, count =>
  404. {
  405. asyncResult.Update(count);
  406. if (listCallback != null)
  407. {
  408. listCallback(count);
  409. }
  410. });
  411. asyncResult.SetAsCompleted(result, false);
  412. }
  413. catch (Exception exp)
  414. {
  415. asyncResult.SetAsCompleted(exp, false);
  416. }
  417. });
  418. return asyncResult;
  419. }
  420. /// <summary>
  421. /// Ends an asynchronous operation of retrieving list of files in remote directory.
  422. /// </summary>
  423. /// <param name="asyncResult">The pending asynchronous SFTP request.</param>
  424. /// <returns>
  425. /// List of files
  426. /// </returns>
  427. /// <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>
  428. public IEnumerable<SftpFile> EndListDirectory(IAsyncResult asyncResult)
  429. {
  430. var ar = asyncResult as SftpListDirectoryAsyncResult;
  431. if (ar == null || ar.EndInvokeCalled)
  432. 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.");
  433. // Wait for operation to complete, then return result or throw exception
  434. return ar.EndInvoke();
  435. }
  436. /// <summary>
  437. /// Gets reference to remote file or directory.
  438. /// </summary>
  439. /// <param name="path">The path.</param>
  440. /// <returns>Reference to <see cref="Renci.SshNet.Sftp.SftpFile"/> file object.</returns>
  441. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  442. /// <exception cref="ArgumentNullException"><paramref name="path" /> is <b>null</b>.</exception>
  443. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  444. public SftpFile Get(string path)
  445. {
  446. CheckDisposed();
  447. if (path == null)
  448. throw new ArgumentNullException("path");
  449. if (this._sftpSession == null)
  450. throw new SshConnectionException("Client not connected.");
  451. var fullPath = this._sftpSession.GetCanonicalPath(path);
  452. var attributes = this._sftpSession.RequestLStat(fullPath);
  453. return new SftpFile(this._sftpSession, fullPath, attributes);
  454. }
  455. /// <summary>
  456. /// Checks whether file or directory exists;
  457. /// </summary>
  458. /// <param name="path">The path.</param>
  459. /// <returns><c>true</c> if directory or file exists; otherwise <c>false</c>.</returns>
  460. /// <exception cref="ArgumentException"><paramref name="path"/> is <b>null</b> or contains whitespace characters.</exception>
  461. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  462. /// <exception cref="SftpPermissionDeniedException">Permission to perform the operation was denied by the remote host. <para>-or-</para> A SSH command was denied by the server.</exception>
  463. /// <exception cref="SshException">A SSH error where <see cref="P:System.Exception.Message"/> is the message from the remote host.</exception>
  464. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  465. public bool Exists(string path)
  466. {
  467. CheckDisposed();
  468. if (path.IsNullOrWhiteSpace())
  469. throw new ArgumentException("path");
  470. if (this._sftpSession == null)
  471. throw new SshConnectionException("Client not connected.");
  472. var fullPath = this._sftpSession.GetCanonicalPath(path);
  473. // using SSH_FXP_REALPATH is not an alternative the SFTP specification has not always
  474. // been clear on how the server should respond when the specified path is not present
  475. // on the server:
  476. //
  477. // SSH 1 to 4:
  478. // No mention of how the server should respond if the path is not present on the server.
  479. //
  480. // SSH 5:
  481. // The server SHOULD fail the request if the path is not present on the server.
  482. //
  483. // SSH 6:
  484. // Draft 06: The server SHOULD fail the request if the path is not present on the server.
  485. // Draft 07 to 13: The server MUST NOT fail the request if the path does not exist.
  486. //
  487. // Note that SSH 6 (draft 06 and forward) allows for more control options, but we
  488. // currently only support up to v3.
  489. try
  490. {
  491. _sftpSession.RequestLStat(fullPath);
  492. return true;
  493. }
  494. catch (SftpPathNotFoundException)
  495. {
  496. return false;
  497. }
  498. }
  499. /// <summary>
  500. /// Downloads remote file specified by the path into the stream.
  501. /// </summary>
  502. /// <param name="path">File to download.</param>
  503. /// <param name="output">Stream to write the file into.</param>
  504. /// <param name="downloadCallback">The download callback.</param>
  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="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="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 void DownloadFile(string path, Stream output, Action<ulong> downloadCallback = null)
  515. {
  516. CheckDisposed();
  517. this.InternalDownloadFile(path, output, null, downloadCallback);
  518. }
  519. /// <summary>
  520. /// Begins an asynchronous file downloading into the stream.
  521. /// </summary>
  522. /// <param name="path">The path.</param>
  523. /// <param name="output">The output.</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="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="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)
  537. {
  538. return this.BeginDownloadFile(path, output, null, 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. /// <returns>
  547. /// An <see cref="IAsyncResult" /> that references the asynchronous operation.
  548. /// </returns>
  549. /// <exception cref="ArgumentNullException"><paramref name="output" /> is <b>null</b>.</exception>
  550. /// <exception cref="ArgumentException"><paramref name="path" /> is <b>null</b> or contains whitespace characters.</exception>
  551. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  552. /// <exception cref="SftpPermissionDeniedException">Permission to perform the operation was denied by the remote host. <para>-or-</para> A SSH command was denied by the server.</exception>
  553. /// <exception cref="SshException">A SSH error where <see cref="P:System.Exception.Message" /> is the message from the remote host.</exception>
  554. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  555. /// <remarks>
  556. /// Method calls made by this method to <paramref name="output" />, may under certain conditions result in exceptions thrown by the stream.
  557. /// </remarks>
  558. public IAsyncResult BeginDownloadFile(string path, Stream output, AsyncCallback asyncCallback)
  559. {
  560. return this.BeginDownloadFile(path, output, asyncCallback, null, null);
  561. }
  562. /// <summary>
  563. /// Begins an asynchronous file downloading into the stream.
  564. /// </summary>
  565. /// <param name="path">The path.</param>
  566. /// <param name="output">The output.</param>
  567. /// <param name="asyncCallback">The method to be called when the asynchronous write operation is completed.</param>
  568. /// <param name="state">A user-provided object that distinguishes this particular asynchronous write request from other requests.</param>
  569. /// <param name="downloadCallback">The download callback.</param>
  570. /// <returns>
  571. /// An <see cref="IAsyncResult" /> that references the asynchronous operation.
  572. /// </returns>
  573. /// <exception cref="ArgumentNullException"><paramref name="output" /> is <b>null</b>.</exception>
  574. /// <exception cref="ArgumentException"><paramref name="path" /> is <b>null</b> or contains whitespace characters.</exception>
  575. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  576. /// <exception cref="SftpPermissionDeniedException">Permission to perform the operation was denied by the remote host. <para>-or-</para> A SSH command was denied by the server.</exception>
  577. /// <exception cref="SshException">A SSH error where <see cref="P:System.Exception.Message" /> is the message from the remote host.</exception>
  578. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  579. /// <remarks>
  580. /// Method calls made by this method to <paramref name="output" />, may under certain conditions result in exceptions thrown by the stream.
  581. /// </remarks>
  582. public IAsyncResult BeginDownloadFile(string path, Stream output, AsyncCallback asyncCallback, object state, Action<ulong> downloadCallback = null)
  583. {
  584. CheckDisposed();
  585. if (path.IsNullOrWhiteSpace())
  586. throw new ArgumentException("path");
  587. if (output == null)
  588. throw new ArgumentNullException("output");
  589. var asyncResult = new SftpDownloadAsyncResult(asyncCallback, state);
  590. this.ExecuteThread(() =>
  591. {
  592. try
  593. {
  594. this.InternalDownloadFile(path, output, asyncResult, offset =>
  595. {
  596. asyncResult.Update(offset);
  597. if (downloadCallback != null)
  598. {
  599. downloadCallback(offset);
  600. }
  601. });
  602. asyncResult.SetAsCompleted(null, false);
  603. }
  604. catch (Exception exp)
  605. {
  606. asyncResult.SetAsCompleted(exp, false);
  607. }
  608. });
  609. return asyncResult;
  610. }
  611. /// <summary>
  612. /// Ends an asynchronous file downloading into the stream.
  613. /// </summary>
  614. /// <param name="asyncResult">The pending asynchronous SFTP request.</param>
  615. /// <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>
  616. public void EndDownloadFile(IAsyncResult asyncResult)
  617. {
  618. var ar = asyncResult as SftpDownloadAsyncResult;
  619. if (ar == null || ar.EndInvokeCalled)
  620. 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.");
  621. // Wait for operation to complete, then return result or throw exception
  622. ar.EndInvoke();
  623. }
  624. /// <summary>
  625. /// Uploads stream into remote file.
  626. /// </summary>
  627. /// <param name="input">Data input stream.</param>
  628. /// <param name="path">Remote file path.</param>
  629. /// <param name="uploadCallback">The upload callback.</param>
  630. /// <exception cref="ArgumentNullException"><paramref name="input" /> is <b>null</b>.</exception>
  631. /// <exception cref="ArgumentException"><paramref name="path" /> is <b>null</b> or contains whitespace characters.</exception>
  632. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  633. /// <exception cref="SftpPermissionDeniedException">Permission to upload the file was denied by the remote host. <para>-or-</para> A SSH command was denied by the server.</exception>
  634. /// <exception cref="SshException">A SSH error where <see cref="P:System.Exception.Message" /> is the message from the remote host.</exception>
  635. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  636. /// <remarks>
  637. /// Method calls made by this method to <paramref name="input" />, may under certain conditions result in exceptions thrown by the stream.
  638. /// </remarks>
  639. public void UploadFile(Stream input, string path, Action<ulong> uploadCallback = null)
  640. {
  641. this.UploadFile(input, path, true, uploadCallback);
  642. }
  643. /// <summary>
  644. /// Uploads stream into remote file.
  645. /// </summary>
  646. /// <param name="input">Data input stream.</param>
  647. /// <param name="path">Remote file path.</param>
  648. /// <param name="canOverride">if set to <c>true</c> then existing file will be overwritten.</param>
  649. /// <param name="uploadCallback">The upload callback.</param>
  650. /// <exception cref="ArgumentNullException"><paramref name="input" /> is <b>null</b>.</exception>
  651. /// <exception cref="ArgumentException"><paramref name="path" /> is <b>null</b> or contains whitespace characters.</exception>
  652. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  653. /// <exception cref="SftpPermissionDeniedException">Permission to upload the file was denied by the remote host. <para>-or-</para> A SSH command was denied by the server.</exception>
  654. /// <exception cref="SshException">A SSH error where <see cref="P:System.Exception.Message" /> is the message from the remote host.</exception>
  655. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  656. /// <remarks>
  657. /// Method calls made by this method to <paramref name="input" />, may under certain conditions result in exceptions thrown by the stream.
  658. /// </remarks>
  659. public void UploadFile(Stream input, string path, bool canOverride, Action<ulong> uploadCallback = null)
  660. {
  661. CheckDisposed();
  662. var flags = Flags.Write | Flags.Truncate;
  663. if (canOverride)
  664. flags |= Flags.CreateNewOrOpen;
  665. else
  666. flags |= Flags.CreateNew;
  667. this.InternalUploadFile(input, path, flags, null, uploadCallback);
  668. }
  669. /// <summary>
  670. /// Begins an asynchronous uploading the steam into remote file.
  671. /// </summary>
  672. /// <param name="input">Data input stream.</param>
  673. /// <param name="path">Remote file path.</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="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="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)
  687. {
  688. return this.BeginUploadFile(input, path, true, null, 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. /// <returns>
  697. /// An <see cref="IAsyncResult" /> that references the asynchronous operation.
  698. /// </returns>
  699. /// <exception cref="ArgumentNullException"><paramref name="input" /> is <b>null</b>.</exception>
  700. /// <exception cref="ArgumentException"><paramref name="path" /> is <b>null</b> or contains whitespace characters.</exception>
  701. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  702. /// <exception cref="SftpPermissionDeniedException">Permission to list the contents of the directory was denied by the remote host. <para>-or-</para> A SSH command was denied by the server.</exception>
  703. /// <exception cref="SshException">A SSH error where <see cref="P:System.Exception.Message" /> is the message from the remote host.</exception>
  704. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  705. /// <remarks>
  706. /// Method calls made by this method to <paramref name="input" />, may under certain conditions result in exceptions thrown by the stream.
  707. /// </remarks>
  708. public IAsyncResult BeginUploadFile(Stream input, string path, AsyncCallback asyncCallback)
  709. {
  710. return this.BeginUploadFile(input, path, true, asyncCallback, null, null);
  711. }
  712. /// <summary>
  713. /// Begins an asynchronous uploading the steam into remote file.
  714. /// </summary>
  715. /// <param name="input">Data input stream.</param>
  716. /// <param name="path">Remote file path.</param>
  717. /// <param name="asyncCallback">The method to be called when the asynchronous write operation is completed.</param>
  718. /// <param name="state">A user-provided object that distinguishes this particular asynchronous write request from other requests.</param>
  719. /// <param name="uploadCallback">The upload callback.</param>
  720. /// <returns>
  721. /// An <see cref="IAsyncResult" /> that references the asynchronous operation.
  722. /// </returns>
  723. /// <exception cref="ArgumentNullException"><paramref name="input" /> is <b>null</b>.</exception>
  724. /// <exception cref="ArgumentException"><paramref name="path" /> is <b>null</b> or contains whitespace characters.</exception>
  725. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  726. /// <exception cref="SftpPermissionDeniedException">Permission to list the contents of the directory was denied by the remote host. <para>-or-</para> A SSH command was denied by the server.</exception>
  727. /// <exception cref="SshException">A SSH error where <see cref="P:System.Exception.Message" /> is the message from the remote host.</exception>
  728. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  729. /// <remarks>
  730. /// Method calls made by this method to <paramref name="input" />, may under certain conditions result in exceptions thrown by the stream.
  731. /// </remarks>
  732. public IAsyncResult BeginUploadFile(Stream input, string path, AsyncCallback asyncCallback, object state, Action<ulong> uploadCallback = null)
  733. {
  734. return this.BeginUploadFile(input, path, true, asyncCallback, state, uploadCallback);
  735. }
  736. /// <summary>
  737. /// Begins an asynchronous uploading the steam into remote file.
  738. /// </summary>
  739. /// <param name="input">Data input stream.</param>
  740. /// <param name="path">Remote file path.</param>
  741. /// <param name="canOverride">if set to <c>true</c> then existing file will be overwritten.</param>
  742. /// <param name="asyncCallback">The method to be called when the asynchronous write operation is completed.</param>
  743. /// <param name="state">A user-provided object that distinguishes this particular asynchronous write request from other requests.</param>
  744. /// <param name="uploadCallback">The upload callback.</param>
  745. /// <returns>
  746. /// An <see cref="IAsyncResult" /> that references the asynchronous operation.
  747. /// </returns>
  748. /// <exception cref="ArgumentNullException"><paramref name="input" /> is <b>null</b>.</exception>
  749. /// <exception cref="ArgumentException"><paramref name="path" /> is <b>null</b> or contains whitespace characters.</exception>
  750. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  751. /// <exception cref="SftpPermissionDeniedException">Permission to list the contents of the directory was denied by the remote host. <para>-or-</para> A SSH command was denied by the server.</exception>
  752. /// <exception cref="SshException">A SSH error where <see cref="P:System.Exception.Message" /> is the message from the remote host.</exception>
  753. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  754. /// <remarks>
  755. /// Method calls made by this method to <paramref name="input" />, may under certain conditions result in exceptions thrown by the stream.
  756. /// </remarks>
  757. public IAsyncResult BeginUploadFile(Stream input, string path, bool canOverride, AsyncCallback asyncCallback, object state, Action<ulong> uploadCallback = null)
  758. {
  759. CheckDisposed();
  760. if (input == null)
  761. throw new ArgumentNullException("input");
  762. if (path.IsNullOrWhiteSpace())
  763. throw new ArgumentException("path");
  764. var flags = Flags.Write | Flags.Truncate;
  765. if (canOverride)
  766. flags |= Flags.CreateNewOrOpen;
  767. else
  768. flags |= Flags.CreateNew;
  769. var asyncResult = new SftpUploadAsyncResult(asyncCallback, state);
  770. this.ExecuteThread(() =>
  771. {
  772. try
  773. {
  774. this.InternalUploadFile(input, path, flags, asyncResult, offset =>
  775. {
  776. asyncResult.Update(offset);
  777. if (uploadCallback != null)
  778. {
  779. uploadCallback(offset);
  780. }
  781. });
  782. asyncResult.SetAsCompleted(null, false);
  783. }
  784. catch (Exception exp)
  785. {
  786. asyncResult.SetAsCompleted(exp, false);
  787. }
  788. });
  789. return asyncResult;
  790. }
  791. /// <summary>
  792. /// Ends an asynchronous uploading the steam into remote file.
  793. /// </summary>
  794. /// <param name="asyncResult">The pending asynchronous SFTP request.</param>
  795. /// <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>
  796. /// <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>
  797. public void EndUploadFile(IAsyncResult asyncResult)
  798. {
  799. var ar = asyncResult as SftpUploadAsyncResult;
  800. if (ar == null || ar.EndInvokeCalled)
  801. 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.");
  802. // Wait for operation to complete, then return result or throw exception
  803. ar.EndInvoke();
  804. }
  805. /// <summary>
  806. /// Gets status using statvfs@openssh.com request.
  807. /// </summary>
  808. /// <param name="path">The path.</param>
  809. /// <returns>Reference to <see cref="Renci.SshNet.Sftp.SftpFileSytemInformation"/> object that contains file status information.</returns>
  810. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  811. /// <exception cref="ArgumentNullException"><paramref name="path" /> is <b>null</b>.</exception>
  812. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  813. public SftpFileSytemInformation GetStatus(string path)
  814. {
  815. CheckDisposed();
  816. if (path == null)
  817. throw new ArgumentNullException("path");
  818. if (this._sftpSession == null)
  819. throw new SshConnectionException("Client not connected.");
  820. var fullPath = this._sftpSession.GetCanonicalPath(path);
  821. return this._sftpSession.RequestStatVfs(fullPath);
  822. }
  823. #region File Methods
  824. /// <summary>
  825. /// Appends lines to a file, and then closes the file.
  826. /// </summary>
  827. /// <param name="path">The file to append the lines to. The file is created if it does not already exist.</param>
  828. /// <param name="contents">The lines to append to the file.</param>
  829. /// <exception cref="ArgumentNullException"><paramref name="path"/> is<b>null</b> <para>-or-</para> <paramref name="contents"/> is <b>null</b>.</exception>
  830. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  831. public void AppendAllLines(string path, IEnumerable<string> contents)
  832. {
  833. CheckDisposed();
  834. if (contents == null)
  835. throw new ArgumentNullException("contents");
  836. using (var stream = this.AppendText(path))
  837. {
  838. foreach (var line in contents)
  839. {
  840. stream.WriteLine(line);
  841. }
  842. }
  843. }
  844. /// <summary>
  845. /// Appends lines to a file by using a specified encoding, and then closes the file.
  846. /// </summary>
  847. /// <param name="path">The file to append the lines to. The file is created if it does not already exist.</param>
  848. /// <param name="contents">The lines to append to the file.</param>
  849. /// <param name="encoding">The character encoding to use.</param>
  850. /// <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>
  851. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  852. public void AppendAllLines(string path, IEnumerable<string> contents, Encoding encoding)
  853. {
  854. CheckDisposed();
  855. if (contents == null)
  856. throw new ArgumentNullException("contents");
  857. using (var stream = this.AppendText(path, encoding))
  858. {
  859. foreach (var line in contents)
  860. {
  861. stream.WriteLine(line);
  862. }
  863. }
  864. }
  865. /// <summary>
  866. /// Opens a file, appends the specified string to the file, and then closes the file.
  867. /// If the file does not exist, this method creates a file, writes the specified string to the file, then closes the file.
  868. /// </summary>
  869. /// <param name="path">The file to append the specified string to.</param>
  870. /// <param name="contents">The string to append to the file.</param>
  871. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>. <para>-or-</para> <paramref name="contents"/> is <b>null</b>.</exception>
  872. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  873. public void AppendAllText(string path, string contents)
  874. {
  875. using (var stream = this.AppendText(path))
  876. {
  877. stream.Write(contents);
  878. }
  879. }
  880. /// <summary>
  881. /// Opens a file, appends the specified string to the file, and then closes the file.
  882. /// If the file does not exist, this method creates a file, writes the specified string to the file, then closes the file.
  883. /// </summary>
  884. /// <param name="path">The file to append the specified string to.</param>
  885. /// <param name="contents">The string to append to the file.</param>
  886. /// <param name="encoding">The character encoding to use.</param>
  887. /// <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>
  888. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  889. public void AppendAllText(string path, string contents, Encoding encoding)
  890. {
  891. using (var stream = this.AppendText(path, encoding))
  892. {
  893. stream.Write(contents);
  894. }
  895. }
  896. /// <summary>
  897. /// Creates a <see cref="System.IO.StreamWriter"/> that appends UTF-8 encoded text to an existing file.
  898. /// </summary>
  899. /// <param name="path">The path to the file to append to.</param>
  900. /// <returns>A StreamWriter that appends UTF-8 encoded text to an existing file.</returns>
  901. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  902. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  903. public StreamWriter AppendText(string path)
  904. {
  905. return this.AppendText(path, Encoding.UTF8);
  906. }
  907. /// <summary>
  908. /// Creates a <see cref="System.IO.StreamWriter"/> that appends UTF-8 encoded text to an existing file.
  909. /// </summary>
  910. /// <param name="path">The path to the file to append to.</param>
  911. /// <param name="encoding">The character encoding to use.</param>
  912. /// <returns>
  913. /// A StreamWriter that appends UTF-8 encoded text to an existing file.
  914. /// </returns>
  915. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>. <para>-or-</para> <paramref name="encoding"/> is <b>null</b>.</exception>
  916. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  917. public StreamWriter AppendText(string path, Encoding encoding)
  918. {
  919. CheckDisposed();
  920. if (encoding == null)
  921. throw new ArgumentNullException("encoding");
  922. return new StreamWriter(new SftpFileStream(this._sftpSession, path, FileMode.Append, FileAccess.Write), encoding);
  923. }
  924. /// <summary>
  925. /// Creates or overwrites a file in the specified path.
  926. /// </summary>
  927. /// <param name="path">The path and name of the file to create.</param>
  928. /// <returns>A <see cref="SftpFileStream"/> that provides read/write access to the file specified in path</returns>
  929. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  930. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  931. public SftpFileStream Create(string path)
  932. {
  933. CheckDisposed();
  934. return new SftpFileStream(this._sftpSession, path, FileMode.Create, FileAccess.ReadWrite);
  935. }
  936. /// <summary>
  937. /// Creates or overwrites the specified file.
  938. /// </summary>
  939. /// <param name="path">The path and name of the file to create.</param>
  940. /// <param name="bufferSize">The number of bytes buffered for reads and writes to the file.</param>
  941. /// <returns>A <see cref="SftpFileStream"/> that provides read/write access to the file specified in path</returns>
  942. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  943. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  944. public SftpFileStream Create(string path, int bufferSize)
  945. {
  946. CheckDisposed();
  947. return new SftpFileStream(this._sftpSession, path, FileMode.Create, FileAccess.ReadWrite, bufferSize);
  948. }
  949. /// <summary>
  950. /// Creates or opens a file for writing UTF-8 encoded text.
  951. /// </summary>
  952. /// <param name="path">The file to be opened for writing.</param>
  953. /// <returns>A <see cref="System.IO.StreamWriter"/> that writes to the specified file using UTF-8 encoding.</returns>
  954. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  955. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  956. public StreamWriter CreateText(string path)
  957. {
  958. return CreateText(path, Encoding.UTF8);
  959. }
  960. /// <summary>
  961. /// Creates or opens a file for writing UTF-8 encoded text.
  962. /// </summary>
  963. /// <param name="path">The file to be opened for writing.</param>
  964. /// <param name="encoding">The character encoding to use.</param>
  965. /// <returns> A <see cref="System.IO.StreamWriter"/> that writes to the specified file using UTF-8 encoding. </returns>
  966. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  967. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  968. public StreamWriter CreateText(string path, Encoding encoding)
  969. {
  970. CheckDisposed();
  971. return new StreamWriter(this.OpenWrite(path), encoding);
  972. }
  973. /// <summary>
  974. /// Deletes the specified file or directory.
  975. /// </summary>
  976. /// <param name="path">The name of the file or directory to be deleted. Wildcard characters are not supported.</param>
  977. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  978. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  979. /// <exception cref="SftpPathNotFoundException"><paramref name="path"/> does not exist.</exception>
  980. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  981. public void Delete(string path)
  982. {
  983. var file = this.Get(path);
  984. file.Delete();
  985. }
  986. /// <summary>
  987. /// Returns the date and time the specified file or directory was last accessed.
  988. /// </summary>
  989. /// <param name="path">The file or directory for which to obtain access date and time information.</param>
  990. /// <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>
  991. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  992. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  993. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  994. public DateTime GetLastAccessTime(string path)
  995. {
  996. var file = this.Get(path);
  997. return file.LastAccessTime;
  998. }
  999. /// <summary>
  1000. /// Returns the date and time, in coordinated universal time (UTC), that the specified file or directory was last accessed.
  1001. /// </summary>
  1002. /// <param name="path">The file or directory for which to obtain access date and time information.</param>
  1003. /// <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>
  1004. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  1005. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  1006. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1007. public DateTime GetLastAccessTimeUtc(string path)
  1008. {
  1009. var lastAccessTime = GetLastAccessTime(path);
  1010. return lastAccessTime.ToUniversalTime();
  1011. }
  1012. /// <summary>
  1013. /// Returns the date and time the specified file or directory was last written to.
  1014. /// </summary>
  1015. /// <param name="path">The file or directory for which to obtain write date and time information.</param>
  1016. /// <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>
  1017. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  1018. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  1019. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1020. public DateTime GetLastWriteTime(string path)
  1021. {
  1022. var file = this.Get(path);
  1023. return file.LastWriteTime;
  1024. }
  1025. /// <summary>
  1026. /// Returns the date and time, in coordinated universal time (UTC), that the specified file or directory was last written to.
  1027. /// </summary>
  1028. /// <param name="path">The file or directory for which to obtain write date and time information.</param>
  1029. /// <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>
  1030. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  1031. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  1032. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1033. public DateTime GetLastWriteTimeUtc(string path)
  1034. {
  1035. var lastWriteTime = GetLastWriteTime(path);
  1036. return lastWriteTime.ToUniversalTime();
  1037. }
  1038. /// <summary>
  1039. /// Opens a <see cref="SftpFileStream"/> on the specified path with read/write access.
  1040. /// </summary>
  1041. /// <param name="path">The file to open.</param>
  1042. /// <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>
  1043. /// <returns>An unshared <see cref="SftpFileStream"/> that provides access to the specified file, with the specified mode and access.</returns>
  1044. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  1045. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1046. public SftpFileStream Open(string path, FileMode mode)
  1047. {
  1048. return Open(path, mode, FileAccess.ReadWrite);
  1049. }
  1050. /// <summary>
  1051. /// Opens a <see cref="SftpFileStream"/> on the specified path, with the specified mode and access.
  1052. /// </summary>
  1053. /// <param name="path">The file to open.</param>
  1054. /// <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>
  1055. /// <param name="access">A <see cref="System.IO.FileAccess"/> value that specifies the operations that can be performed on the file.</param>
  1056. /// <returns>An unshared <see cref="SftpFileStream"/> that provides access to the specified file, with the specified mode and access.</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 SftpFileStream Open(string path, FileMode mode, FileAccess access)
  1060. {
  1061. CheckDisposed();
  1062. return new SftpFileStream(this._sftpSession, path, mode, access, (int) _bufferSize);
  1063. }
  1064. /// <summary>
  1065. /// Opens an existing file for reading.
  1066. /// </summary>
  1067. /// <param name="path">The file to be opened for reading.</param>
  1068. /// <returns>A read-only System.IO.FileStream on the specified path.</returns>
  1069. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  1070. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1071. public SftpFileStream OpenRead(string path)
  1072. {
  1073. return Open(path, FileMode.Open, FileAccess.Read);
  1074. }
  1075. /// <summary>
  1076. /// Opens an existing UTF-8 encoded text file for reading.
  1077. /// </summary>
  1078. /// <param name="path">The file to be opened for reading.</param>
  1079. /// <returns>A <see cref="System.IO.StreamReader"/> on the specified path.</returns>
  1080. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  1081. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1082. public StreamReader OpenText(string path)
  1083. {
  1084. return new StreamReader(this.OpenRead(path), Encoding.UTF8);
  1085. }
  1086. /// <summary>
  1087. /// Opens an existing file for writing.
  1088. /// </summary>
  1089. /// <param name="path">The file to be opened for writing.</param>
  1090. /// <returns>An unshared <see cref="SftpFileStream"/> object on the specified path with <see cref="System.IO.FileAccess.Write"/> access.</returns>
  1091. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  1092. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1093. public SftpFileStream OpenWrite(string path)
  1094. {
  1095. CheckDisposed();
  1096. return new SftpFileStream(this._sftpSession, path, FileMode.OpenOrCreate, FileAccess.Write,
  1097. (int) _bufferSize);
  1098. }
  1099. /// <summary>
  1100. /// Opens a binary file, reads the contents of the file into a byte array, and then closes the file.
  1101. /// </summary>
  1102. /// <param name="path">The file to open for reading.</param>
  1103. /// <returns>A byte array containing the contents of the file.</returns>
  1104. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  1105. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1106. public byte[] ReadAllBytes(string path)
  1107. {
  1108. using (var stream = this.OpenRead(path))
  1109. {
  1110. var buffer = new byte[stream.Length];
  1111. stream.Read(buffer, 0, buffer.Length);
  1112. return buffer;
  1113. }
  1114. }
  1115. /// <summary>
  1116. /// Opens a text file, reads all lines of the file, and then closes the file.
  1117. /// </summary>
  1118. /// <param name="path">The file to open for reading.</param>
  1119. /// <returns>A string array containing all lines of the file.</returns>
  1120. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  1121. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1122. public string[] ReadAllLines(string path)
  1123. {
  1124. return this.ReadAllLines(path, Encoding.UTF8);
  1125. }
  1126. /// <summary>
  1127. /// Opens a file, reads all lines of the file with the specified encoding, and then closes the file.
  1128. /// </summary>
  1129. /// <param name="path">The file to open for reading.</param>
  1130. /// <param name="encoding">The encoding applied to the contents of the file.</param>
  1131. /// <returns>A string array containing all lines of the file.</returns>
  1132. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  1133. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1134. public string[] ReadAllLines(string path, Encoding encoding)
  1135. {
  1136. var lines = new List<string>();
  1137. using (var stream = new StreamReader(this.OpenRead(path), encoding))
  1138. {
  1139. while (!stream.EndOfStream)
  1140. {
  1141. lines.Add(stream.ReadLine());
  1142. }
  1143. }
  1144. return lines.ToArray();
  1145. }
  1146. /// <summary>
  1147. /// Opens a text file, reads all lines of the file, and then closes the file.
  1148. /// </summary>
  1149. /// <param name="path">The file to open for reading.</param>
  1150. /// <returns>A string containing all lines of the file.</returns>
  1151. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  1152. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1153. public string ReadAllText(string path)
  1154. {
  1155. return this.ReadAllText(path, Encoding.UTF8);
  1156. }
  1157. /// <summary>
  1158. /// Opens a file, reads all lines of the file with the specified encoding, and then closes the file.
  1159. /// </summary>
  1160. /// <param name="path">The file to open for reading.</param>
  1161. /// <param name="encoding">The encoding applied to the contents of the file.</param>
  1162. /// <returns>A string containing all lines of the file.</returns>
  1163. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  1164. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1165. public string ReadAllText(string path, Encoding encoding)
  1166. {
  1167. using (var stream = new StreamReader(this.OpenRead(path), encoding))
  1168. {
  1169. return stream.ReadToEnd();
  1170. }
  1171. }
  1172. /// <summary>
  1173. /// Reads the lines of a file.
  1174. /// </summary>
  1175. /// <param name="path">The file to read.</param>
  1176. /// <returns>The lines of the file.</returns>
  1177. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  1178. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1179. public IEnumerable<string> ReadLines(string path)
  1180. {
  1181. return this.ReadAllLines(path);
  1182. }
  1183. /// <summary>
  1184. /// Read the lines of a file that has a specified encoding.
  1185. /// </summary>
  1186. /// <param name="path">The file to read.</param>
  1187. /// <param name="encoding">The encoding that is applied to the contents of the file.</param>
  1188. /// <returns>The lines of the file.</returns>
  1189. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  1190. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1191. public IEnumerable<string> ReadLines(string path, Encoding encoding)
  1192. {
  1193. return this.ReadAllLines(path, encoding);
  1194. }
  1195. /// <summary>
  1196. /// Sets the date and time the specified file was last accessed.
  1197. /// </summary>
  1198. /// <param name="path">The file for which to set the access date and time information.</param>
  1199. /// <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>
  1200. [Obsolete("Note: This method currently throws NotImplementedException because it has not yet been implemented.")]
  1201. public void SetLastAccessTime(string path, DateTime lastAccessTime)
  1202. {
  1203. throw new NotImplementedException();
  1204. }
  1205. /// <summary>
  1206. /// Sets the date and time, in coordinated universal time (UTC), that the specified file was last accessed.
  1207. /// </summary>
  1208. /// <param name="path">The file for which to set the access date and time information.</param>
  1209. /// <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>
  1210. [Obsolete("Note: This method currently throws NotImplementedException because it has not yet been implemented.")]
  1211. public void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc)
  1212. {
  1213. throw new NotImplementedException();
  1214. }
  1215. /// <summary>
  1216. /// Sets the date and time that the specified file was last written to.
  1217. /// </summary>
  1218. /// <param name="path">The file for which to set the date and time information.</param>
  1219. /// <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>
  1220. [Obsolete("Note: This method currently throws NotImplementedException because it has not yet been implemented.")]
  1221. public void SetLastWriteTime(string path, DateTime lastWriteTime)
  1222. {
  1223. throw new NotImplementedException();
  1224. }
  1225. /// <summary>
  1226. /// Sets the date and time, in coordinated universal time (UTC), that the specified file was last written to.
  1227. /// </summary>
  1228. /// <param name="path">The file for which to set the date and time information.</param>
  1229. /// <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>
  1230. [Obsolete("Note: This method currently throws NotImplementedException because it has not yet been implemented.")]
  1231. public void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc)
  1232. {
  1233. throw new NotImplementedException();
  1234. }
  1235. /// <summary>
  1236. /// 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.
  1237. /// </summary>
  1238. /// <param name="path">The file to write to.</param>
  1239. /// <param name="bytes">The bytes to write to the file.</param>
  1240. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  1241. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1242. public void WriteAllBytes(string path, byte[] bytes)
  1243. {
  1244. using (var stream = this.OpenWrite(path))
  1245. {
  1246. stream.Write(bytes, 0, bytes.Length);
  1247. }
  1248. }
  1249. /// <summary>
  1250. /// Creates a new file, writes a collection of strings to the file, and then closes the file.
  1251. /// </summary>
  1252. /// <param name="path">The file to write to.</param>
  1253. /// <param name="contents">The lines to write to the file.</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)
  1257. {
  1258. this.WriteAllLines(path, contents, Encoding.UTF8);
  1259. }
  1260. /// <summary>
  1261. /// Creates a new file, write the specified string array to the file, and then closes the file.
  1262. /// </summary>
  1263. /// <param name="path">The file to write to.</param>
  1264. /// <param name="contents">The string array to write to the file.</param>
  1265. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  1266. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1267. public void WriteAllLines(string path, string[] contents)
  1268. {
  1269. this.WriteAllLines(path, contents, Encoding.UTF8);
  1270. }
  1271. /// <summary>
  1272. /// Creates a new file by using the specified encoding, writes a collection of strings to the file, and then closes the file.
  1273. /// </summary>
  1274. /// <param name="path">The file to write to.</param>
  1275. /// <param name="contents">The lines to write to the file.</param>
  1276. /// <param name="encoding">The character encoding to use.</param>
  1277. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  1278. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1279. public void WriteAllLines(string path, IEnumerable<string> contents, Encoding encoding)
  1280. {
  1281. using (var stream = this.CreateText(path, encoding))
  1282. {
  1283. foreach (var line in contents)
  1284. {
  1285. stream.WriteLine(line);
  1286. }
  1287. }
  1288. }
  1289. /// <summary>
  1290. /// Creates a new file, writes the specified string array to the file by using the specified encoding, and then closes the file.
  1291. /// </summary>
  1292. /// <param name="path">The file to write to.</param>
  1293. /// <param name="contents">The string array to write to the file.</param>
  1294. /// <param name="encoding">An <see cref="System.Text.Encoding"/> object that represents the character encoding applied to the string array.</param>
  1295. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  1296. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1297. public void WriteAllLines(string path, string[] contents, Encoding encoding)
  1298. {
  1299. using (var stream = this.CreateText(path, encoding))
  1300. {
  1301. foreach (var line in contents)
  1302. {
  1303. stream.WriteLine(line);
  1304. }
  1305. }
  1306. }
  1307. /// <summary>
  1308. /// 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.
  1309. /// </summary>
  1310. /// <param name="path">The file to write to.</param>
  1311. /// <param name="contents">The string to write to the file.</param>
  1312. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  1313. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1314. public void WriteAllText(string path, string contents)
  1315. {
  1316. using (var stream = this.CreateText(path))
  1317. {
  1318. stream.Write(contents);
  1319. }
  1320. }
  1321. /// <summary>
  1322. /// 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.
  1323. /// </summary>
  1324. /// <param name="path">The file to write to.</param>
  1325. /// <param name="contents">The string to write to the file.</param>
  1326. /// <param name="encoding">The encoding to apply to the string.</param>
  1327. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  1328. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1329. public void WriteAllText(string path, string contents, Encoding encoding)
  1330. {
  1331. using (var stream = this.CreateText(path, encoding))
  1332. {
  1333. stream.Write(contents);
  1334. }
  1335. }
  1336. /// <summary>
  1337. /// Gets the <see cref="SftpFileAttributes"/> of the file on the path.
  1338. /// </summary>
  1339. /// <param name="path">The path to the file.</param>
  1340. /// <returns>The <see cref="SftpFileAttributes"/> of the file on the path.</returns>
  1341. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  1342. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1343. public SftpFileAttributes GetAttributes(string path)
  1344. {
  1345. CheckDisposed();
  1346. if (this._sftpSession == null)
  1347. throw new SshConnectionException("Client not connected.");
  1348. var fullPath = this._sftpSession.GetCanonicalPath(path);
  1349. return this._sftpSession.RequestLStat(fullPath);
  1350. }
  1351. /// <summary>
  1352. /// Sets the specified <see cref="SftpFileAttributes"/> of the file on the specified path.
  1353. /// </summary>
  1354. /// <param name="path">The path to the file.</param>
  1355. /// <param name="fileAttributes">The desired <see cref="SftpFileAttributes"/>.</param>
  1356. /// <exception cref="ArgumentNullException"><paramref name="path"/> is <b>null</b>.</exception>
  1357. /// <exception cref="ObjectDisposedException">The method was called after the client was disposed.</exception>
  1358. public void SetAttributes(string path, SftpFileAttributes fileAttributes)
  1359. {
  1360. CheckDisposed();
  1361. if (this._sftpSession == null)
  1362. throw new SshConnectionException("Client not connected.");
  1363. var fullPath = this._sftpSession.GetCanonicalPath(path);
  1364. this._sftpSession.RequestSetStat(fullPath, fileAttributes);
  1365. }
  1366. // Please don't forget this when you implement these methods: <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception>
  1367. //public FileSecurity GetAccessControl(string path);
  1368. //public FileSecurity GetAccessControl(string path, AccessControlSections includeSections);
  1369. //public DateTime GetCreationTime(string path);
  1370. //public DateTime GetCreationTimeUtc(string path);
  1371. //public void SetAccessControl(string path, FileSecurity fileSecurity);
  1372. //public void SetCreationTime(string path, DateTime creationTime);
  1373. //public void SetCreationTimeUtc(string path, DateTime creationTimeUtc);
  1374. #endregion
  1375. /// <summary>
  1376. /// Internals the list directory.
  1377. /// </summary>
  1378. /// <param name="path">The path.</param>
  1379. /// <param name="listCallback">The list callback.</param>
  1380. /// <returns></returns>
  1381. /// <exception cref="System.ArgumentNullException">path</exception>
  1382. /// <exception cref="ArgumentNullException"><paramref name="path" /> is <b>null</b>.</exception>
  1383. /// <exception cref="SshConnectionException">Client not connected.</exception>
  1384. private IEnumerable<SftpFile> InternalListDirectory(string path, Action<int> listCallback)
  1385. {
  1386. if (path == null)
  1387. throw new ArgumentNullException("path");
  1388. if (this._sftpSession == null)
  1389. throw new SshConnectionException("Client not connected.");
  1390. var fullPath = this._sftpSession.GetCanonicalPath(path);
  1391. var handle = this._sftpSession.RequestOpenDir(fullPath);
  1392. var basePath = fullPath;
  1393. if (!basePath.EndsWith("/"))
  1394. basePath = string.Format("{0}/", fullPath);
  1395. var result = new List<SftpFile>();
  1396. var files = this._sftpSession.RequestReadDir(handle);
  1397. while (files != null)
  1398. {
  1399. result.AddRange(from f in files
  1400. select new SftpFile(this._sftpSession, string.Format(CultureInfo.InvariantCulture, "{0}{1}", basePath, f.Key), f.Value));
  1401. // Call callback to report number of files read
  1402. if (listCallback != null)
  1403. {
  1404. // Execute callback on different thread
  1405. this.ExecuteThread(() => listCallback(result.Count));
  1406. }
  1407. files = this._sftpSession.RequestReadDir(handle);
  1408. }
  1409. this._sftpSession.RequestClose(handle);
  1410. return result;
  1411. }
  1412. /// <summary>
  1413. /// Internals the download file.
  1414. /// </summary>
  1415. /// <param name="path">The path.</param>
  1416. /// <param name="output">The output.</param>
  1417. /// <param name="asyncResult">An <see cref="IAsyncResult"/> that references the asynchronous request.</param>
  1418. /// <param name="downloadCallback">The download callback.</param>
  1419. /// <exception cref="ArgumentNullException"><paramref name="output" /> is <b>null</b>.</exception>
  1420. /// <exception cref="ArgumentException"><paramref name="path" /> is <b>null</b> or contains whitespace.</exception>
  1421. /// <exception cref="SshConnectionException">Client not connected.</exception>
  1422. private void InternalDownloadFile(string path, Stream output, SftpDownloadAsyncResult asyncResult, Action<ulong> downloadCallback)
  1423. {
  1424. if (output == null)
  1425. throw new ArgumentNullException("output");
  1426. if (path.IsNullOrWhiteSpace())
  1427. throw new ArgumentException("path");
  1428. if (this._sftpSession == null)
  1429. throw new SshConnectionException("Client not connected.");
  1430. var fullPath = this._sftpSession.GetCanonicalPath(path);
  1431. var handle = this._sftpSession.RequestOpen(fullPath, Flags.Read);
  1432. ulong offset = 0;
  1433. var optimalReadLength = _sftpSession.CalculateOptimalReadLength(_bufferSize);
  1434. var data = this._sftpSession.RequestRead(handle, offset, optimalReadLength);
  1435. // Read data while available
  1436. while (data.Length > 0)
  1437. {
  1438. // Cancel download
  1439. if (asyncResult != null && asyncResult.IsDownloadCanceled)
  1440. break;
  1441. output.Write(data, 0, data.Length);
  1442. output.Flush();
  1443. offset += (ulong)data.Length;
  1444. // Call callback to report number of bytes read
  1445. if (downloadCallback != null)
  1446. {
  1447. // Execute callback on different thread
  1448. this.ExecuteThread(() => { downloadCallback(offset); });
  1449. }
  1450. data = this._sftpSession.RequestRead(handle, offset, optimalReadLength);
  1451. }
  1452. this._sftpSession.RequestClose(handle);
  1453. }
  1454. /// <summary>
  1455. /// Internals the upload file.
  1456. /// </summary>
  1457. /// <param name="input">The input.</param>
  1458. /// <param name="path">The path.</param>
  1459. /// <param name="flags">The flags.</param>
  1460. /// <param name="asyncResult">An <see cref="IAsyncResult"/> that references the asynchronous request.</param>
  1461. /// <param name="uploadCallback">The upload callback.</param>
  1462. /// <exception cref="ArgumentNullException"><paramref name="input" /> is <b>null</b>.</exception>
  1463. /// <exception cref="ArgumentException"><paramref name="path" /> is <b>null</b> or contains whitespace.</exception>
  1464. /// <exception cref="SshConnectionException">Client not connected.</exception>
  1465. private void InternalUploadFile(Stream input, string path, Flags flags, SftpUploadAsyncResult asyncResult, Action<ulong> uploadCallback)
  1466. {
  1467. if (input == null)
  1468. throw new ArgumentNullException("input");
  1469. if (path.IsNullOrWhiteSpace())
  1470. throw new ArgumentException("path");
  1471. if (this._sftpSession == null)
  1472. throw new SshConnectionException("Client not connected.");
  1473. var fullPath = this._sftpSession.GetCanonicalPath(path);
  1474. var handle = this._sftpSession.RequestOpen(fullPath, flags);
  1475. ulong offset = 0;
  1476. // create buffer of optimal length
  1477. var buffer = new byte[_sftpSession.CalculateOptimalWriteLength(_bufferSize, handle)];
  1478. var bytesRead = input.Read(buffer, 0, buffer.Length);
  1479. var expectedResponses = 0;
  1480. var responseReceivedWaitHandle = new AutoResetEvent(false);
  1481. do
  1482. {
  1483. // Cancel upload
  1484. if (asyncResult != null && asyncResult.IsUploadCanceled)
  1485. break;
  1486. if (bytesRead > 0)
  1487. {
  1488. if (bytesRead < buffer.Length)
  1489. {
  1490. // Replace buffer for last chunk of data
  1491. var data = new byte[bytesRead];
  1492. Buffer.BlockCopy(buffer, 0, data, 0, bytesRead);
  1493. buffer = data;
  1494. }
  1495. var writtenBytes = offset + (ulong)buffer.Length;
  1496. this._sftpSession.RequestWrite(handle, offset, buffer, null, s =>
  1497. {
  1498. if (s.StatusCode == StatusCodes.Ok)
  1499. {
  1500. Interlocked.Decrement(ref expectedResponses);
  1501. responseReceivedWaitHandle.Set();
  1502. // Call callback to report number of bytes written
  1503. if (uploadCallback != null)
  1504. {
  1505. // Execute callback on different thread
  1506. this.ExecuteThread(() => uploadCallback(writtenBytes));
  1507. }
  1508. }
  1509. });
  1510. Interlocked.Increment(ref expectedResponses);
  1511. offset += (uint)bytesRead;
  1512. bytesRead = input.Read(buffer, 0, buffer.Length);
  1513. }
  1514. else if (expectedResponses > 0)
  1515. {
  1516. // Wait for expectedResponses to change
  1517. this._sftpSession.WaitOnHandle(responseReceivedWaitHandle, this.OperationTimeout);
  1518. }
  1519. } while (expectedResponses > 0 || bytesRead > 0);
  1520. this._sftpSession.RequestClose(handle);
  1521. }
  1522. partial void ExecuteThread(Action action);
  1523. /// <summary>
  1524. /// Called when client is connected to the server.
  1525. /// </summary>
  1526. protected override void OnConnected()
  1527. {
  1528. base.OnConnected();
  1529. this._sftpSession = new SftpSession(this.Session, this.OperationTimeout, this.ConnectionInfo.Encoding);
  1530. this._sftpSession.Connect();
  1531. }
  1532. /// <summary>
  1533. /// Called when client is disconnecting from the server.
  1534. /// </summary>
  1535. protected override void OnDisconnecting()
  1536. {
  1537. base.OnDisconnecting();
  1538. // disconnect and dispose the SFTP session
  1539. // the dispose is necessary since we create a new SFTP session
  1540. // on each connect
  1541. if (_sftpSession != null)
  1542. {
  1543. this._sftpSession.Disconnect();
  1544. this._sftpSession.Dispose();
  1545. this._sftpSession = null;
  1546. }
  1547. }
  1548. /// <summary>
  1549. /// Releases unmanaged and - optionally - managed resources
  1550. /// </summary>
  1551. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged ResourceMessages.</param>
  1552. protected override void Dispose(bool disposing)
  1553. {
  1554. if (this._sftpSession != null)
  1555. {
  1556. this._sftpSession.Dispose();
  1557. this._sftpSession = null;
  1558. }
  1559. base.Dispose(disposing);
  1560. }
  1561. }
  1562. }