SftpClient.cs 83 KB

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