SftpClient.cs 95 KB

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