SftpClient.cs 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227
  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. namespace Renci.SshNet
  10. {
  11. /// <summary>
  12. ///
  13. /// </summary>
  14. public partial class SftpClient : BaseClient
  15. {
  16. /// <summary>
  17. /// Holds SftpSession instance that used to communicate to the SFTP server
  18. /// </summary>
  19. private SftpSession _sftpSession;
  20. /// <summary>
  21. /// Gets or sets the operation timeout.
  22. /// </summary>
  23. /// <value>The operation timeout.</value>
  24. public TimeSpan OperationTimeout { get; set; }
  25. /// <summary>
  26. /// Gets or sets the size of the buffer.
  27. /// </summary>
  28. /// <value>The size of the buffer.</value>
  29. public uint BufferSize { get; set; }
  30. /// <summary>
  31. /// Gets remote working directory.
  32. /// </summary>
  33. public string WorkingDirectory
  34. {
  35. get
  36. {
  37. if (this._sftpSession == null)
  38. return null;
  39. return this._sftpSession.WorkingDirectory;
  40. }
  41. }
  42. /// <summary>
  43. /// Gets sftp protocol version.
  44. /// </summary>
  45. public int ProtocolVersion { get; private set; }
  46. #region Constructors
  47. /// <summary>
  48. /// Initializes a new instance of the <see cref="SftpClient"/> class.
  49. /// </summary>
  50. /// <param name="connectionInfo">The connection info.</param>
  51. /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is null.</exception>
  52. public SftpClient(ConnectionInfo connectionInfo)
  53. : base(connectionInfo)
  54. {
  55. this.OperationTimeout = new TimeSpan(0, 0, 0, 0, -1);
  56. this.BufferSize = 1024 * 32 - 38;
  57. }
  58. /// <summary>
  59. /// Initializes a new instance of the <see cref="SftpClient"/> class.
  60. /// </summary>
  61. /// <param name="host">Connection host.</param>
  62. /// <param name="port">Connection port.</param>
  63. /// <param name="username">Authentication username.</param>
  64. /// <param name="password">Authentication password.</param>
  65. /// <exception cref="ArgumentNullException"><paramref name="password"/> is null.</exception>
  66. /// <exception cref="ArgumentException"><paramref name="host"/> is invalid, or <paramref name="username"/> is null or contains whitespace characters.</exception>
  67. /// <exception cref="ArgumentOutOfRangeException"><paramref name="port"/> is not within <see cref="System.Net.IPEndPoint.MinPort"/> and <see cref="System.Net.IPEndPoint.MaxPort"/>.</exception>
  68. public SftpClient(string host, int port, string username, string password)
  69. : this(new PasswordConnectionInfo(host, port, username, password))
  70. {
  71. }
  72. /// <summary>
  73. /// Initializes a new instance of the <see cref="SftpClient"/> class.
  74. /// </summary>
  75. /// <param name="host">Connection host.</param>
  76. /// <param name="username">Authentication username.</param>
  77. /// <param name="password">Authentication password.</param>
  78. /// <exception cref="ArgumentNullException"><paramref name="password"/> is null.</exception>
  79. /// <exception cref="ArgumentException"><paramref name="host"/> is invalid, or <paramref name="username"/> is null or contains whitespace characters.</exception>
  80. public SftpClient(string host, string username, string password)
  81. : this(host, 22, username, password)
  82. {
  83. }
  84. /// <summary>
  85. /// Initializes a new instance of the <see cref="SftpClient"/> class.
  86. /// </summary>
  87. /// <param name="host">Connection host.</param>
  88. /// <param name="port">Connection port.</param>
  89. /// <param name="username">Authentication username.</param>
  90. /// <param name="keyFiles">Authentication private key file(s) .</param>
  91. /// <exception cref="ArgumentNullException"><paramref name="keyFiles"/> is null.</exception>
  92. /// <exception cref="ArgumentException"><paramref name="host"/> is invalid, -or- <paramref name="username"/> is null or contains whitespace characters.</exception>
  93. /// <exception cref="ArgumentOutOfRangeException"><paramref name="port"/> is not within <see cref="System.Net.IPEndPoint.MinPort"/> and <see cref="System.Net.IPEndPoint.MaxPort"/>.</exception>
  94. public SftpClient(string host, int port, string username, params PrivateKeyFile[] keyFiles)
  95. : this(new PrivateKeyConnectionInfo(host, port, username, keyFiles))
  96. {
  97. }
  98. /// <summary>
  99. /// Initializes a new instance of the <see cref="SftpClient"/> class.
  100. /// </summary>
  101. /// <param name="host">Connection host.</param>
  102. /// <param name="username">Authentication username.</param>
  103. /// <param name="keyFiles">Authentication private key file(s) .</param>
  104. /// <exception cref="ArgumentNullException"><paramref name="keyFiles"/> is null.</exception>
  105. /// <exception cref="ArgumentException"><paramref name="host"/> is invalid, -or- <paramref name="username"/> is null or contains whitespace characters.</exception>
  106. public SftpClient(string host, string username, params PrivateKeyFile[] keyFiles)
  107. : this(host, 22, username, keyFiles)
  108. {
  109. }
  110. #endregion
  111. /// <summary>
  112. /// Changes remote directory to path.
  113. /// </summary>
  114. /// <param name="path">New directory path.</param>
  115. /// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception>
  116. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  117. /// <exception cref="SftpPermissionDeniedException">Permission to change directory denied by remote host -or- a SSH command was denied by the server.</exception>
  118. /// <exception cref="SftpPathNotFoundException">The path in <paramref name="path"/> was not found on the remote host.</exception>
  119. /// <exception cref="SshException">A SSH error where <see cref="P:SshException.Message"/> is the message from the remote host.</exception>
  120. public void ChangeDirectory(string path)
  121. {
  122. if (path == null)
  123. throw new ArgumentNullException("path");
  124. // Ensure that connection is established.
  125. this.EnsureConnection();
  126. this._sftpSession.ChangeDirectory(path);
  127. }
  128. /// <summary>
  129. /// Changes permissions of file(s) to specified mode.
  130. /// </summary>
  131. /// <param name="path">File(s) path, may match multiple files.</param>
  132. /// <param name="mode">The mode.</param>
  133. /// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception>
  134. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  135. /// <exception cref="SftpPermissionDeniedException">Permission to change permission on the path(s) was denied by the remote host -or- a SSH command was denied by the server.</exception>
  136. /// <exception cref="SftpPathNotFoundException">The path in <paramref name="path"/> was not found on the remote host.</exception>
  137. /// <exception cref="SshException">A SSH error where <see cref="P:SshException.Message"/> is the message from the remote host.</exception>
  138. public void ChangePermissions(string path, short mode)
  139. {
  140. var file = this.Get(path);
  141. file.SetPermissions(mode);
  142. }
  143. /// <summary>
  144. /// Creates remote directory specified by path.
  145. /// </summary>
  146. /// <param name="path">Directory path to create.</param>
  147. /// <exception cref="ArgumentException"><paramref name="path"/> is null or contains whitespace characters.</exception>
  148. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  149. /// <exception cref="Renci.SshNet.Common.SftpPermissionDeniedException">Permission to create the directory was denied by the remote host -or- a SSH command was denied by the server.</exception>
  150. /// <exception cref="Renci.SshNet.Common.SshException">A SSH error where <see cref="P:SshException.Message"/> is the message from the remote host.</exception>
  151. public void CreateDirectory(string path)
  152. {
  153. if (string.IsNullOrWhiteSpace(path))
  154. throw new ArgumentException(path);
  155. // Ensure that connection is established.
  156. this.EnsureConnection();
  157. var fullPath = this._sftpSession.GetCanonicalPath(path);
  158. this._sftpSession.RequestMkDir(fullPath);
  159. }
  160. /// <summary>
  161. /// Deletes remote directory specified by path.
  162. /// </summary>
  163. /// <param name="path">Directory to be deleted path.</param>
  164. /// <exception cref="ArgumentException"><paramref name="path"/> is null or contains whitespace characters.</exception>
  165. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  166. /// <exception cref="Renci.SshNet.Common.SftpPermissionDeniedException">Permission to delete the directory was denied by the remote host -or- a SSH command was denied by the server.</exception>
  167. /// <exception cref="Renci.SshNet.Common.SshException">A SSH error where <see cref="P:SshException.Message"/> is the message from the remote host.</exception>
  168. public void DeleteDirectory(string path)
  169. {
  170. if (string.IsNullOrWhiteSpace(path))
  171. throw new ArgumentException("path");
  172. // Ensure that connection is established.
  173. this.EnsureConnection();
  174. var fullPath = this._sftpSession.GetCanonicalPath(path);
  175. this._sftpSession.RequestRmDir(fullPath);
  176. }
  177. /// <summary>
  178. /// Deletes remote file specified by path.
  179. /// </summary>
  180. /// <param name="path">File to be deleted path.</param>
  181. /// <exception cref="ArgumentException"><paramref name="path"/> is null or contains whitespace characters.</exception>
  182. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  183. /// <exception cref="Renci.SshNet.Common.SftpPermissionDeniedException">Permission to delete the file was denied by the remote host -or- a SSH command was denied by the server.</exception>
  184. /// <exception cref="Renci.SshNet.Common.SshException">A SSH error where <see cref="P:SshException.Message"/> is the message from the remote host.</exception>
  185. public void DeleteFile(string path)
  186. {
  187. if (string.IsNullOrWhiteSpace(path))
  188. throw new ArgumentException("path");
  189. // Ensure that connection is established.
  190. this.EnsureConnection();
  191. var fullPath = this._sftpSession.GetCanonicalPath(path);
  192. this._sftpSession.RequestRemove(fullPath);
  193. }
  194. /// <summary>
  195. /// Renames remote file from old path to new path.
  196. /// </summary>
  197. /// <param name="oldPath">Path to the old file location.</param>
  198. /// <param name="newPath">Path to the new file location.</param>
  199. /// <exception cref="ArgumentNullException"><paramref name="oldPath"/> or <paramref name="newPath"/> is null.</exception>
  200. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  201. /// <exception cref="Renci.SshNet.Common.SftpPermissionDeniedException">Permission to rename the file was denied by the remote host -or- a SSH command was denied by the server.</exception>
  202. /// <exception cref="Renci.SshNet.Common.SshException">A SSH error where <see cref="P:SshException.Message"/> is the message from the remote host.</exception>
  203. public void RenameFile(string oldPath, string newPath)
  204. {
  205. if (oldPath == null)
  206. throw new ArgumentNullException("oldPath");
  207. if (newPath == null)
  208. throw new ArgumentNullException("newPath");
  209. // Ensure that connection is established.
  210. this.EnsureConnection();
  211. var oldFullPath = this._sftpSession.GetCanonicalPath(oldPath);
  212. var newFullPath = this._sftpSession.GetCanonicalPath(newPath);
  213. this._sftpSession.RequestRename(oldFullPath, newFullPath);
  214. }
  215. /// <summary>
  216. /// Creates a symbolic link from old path to new path.
  217. /// </summary>
  218. /// <param name="path">The old path.</param>
  219. /// <param name="linkPath">The new path.</param>
  220. /// <exception cref="ArgumentException"><paramref name="path"/> or <paramref name="linkPath"/> is null or contains whitespace characters.</exception>
  221. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  222. /// <exception cref="Renci.SshNet.Common.SftpPermissionDeniedException">Permission to create the symbolic link was denied by the remote host -or- a SSH command was denied by the server.</exception>
  223. /// <exception cref="Renci.SshNet.Common.SshException">A SSH error where <see cref="P:SshException.Message"/> is the message from the remote host.</exception>
  224. public void SymbolicLink(string path, string linkPath)
  225. {
  226. if (string.IsNullOrWhiteSpace(path))
  227. throw new ArgumentException("path");
  228. if (string.IsNullOrWhiteSpace(linkPath))
  229. throw new ArgumentException("linkPath");
  230. // Ensure that connection is established.
  231. this.EnsureConnection();
  232. var fullPath = this._sftpSession.GetCanonicalPath(path);
  233. var linkFullPath = this._sftpSession.GetCanonicalPath(linkPath);
  234. this._sftpSession.RequestSymLink(fullPath, linkFullPath);
  235. }
  236. /// <summary>
  237. /// Retrieves list of files in remote directory.
  238. /// </summary>
  239. /// <param name="path">The path.</param>
  240. /// <returns>List of directory entries</returns>
  241. /// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception>
  242. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  243. /// <exception cref="Renci.SshNet.Common.SftpPermissionDeniedException">Permission to list the contents of the directory was denied by the remote host -or- a SSH command was denied by the server.</exception>
  244. /// <exception cref="Renci.SshNet.Common.SshException">A SSH error where <see cref="P:SshException.Message"/> is the message from the remote host.</exception>
  245. public IEnumerable<SftpFile> ListDirectory(string path)
  246. {
  247. return InternalListDirectory(path, null);
  248. }
  249. /// <summary>
  250. /// Begins an asynchronous operation of retrieving list of files in remote directory.
  251. /// </summary>
  252. /// <param name="path">The path.</param>
  253. /// <param name="asyncCallback">The method to be called when the asynchronous write operation is completed.</param>
  254. /// <param name="state">A user-provided object that distinguishes this particular asynchronous write request from other requests.</param>
  255. /// <returns>
  256. /// An <see cref="IAsyncResult"/> that references the asynchronous operation.
  257. /// </returns>
  258. public IAsyncResult BeginListDirectory(string path, AsyncCallback asyncCallback, object state)
  259. {
  260. var asyncResult = new SftpListDirectoryAsyncResult(asyncCallback, state);
  261. this.ExecuteThread(() =>
  262. {
  263. try
  264. {
  265. var result = this.InternalListDirectory(path, asyncResult);
  266. asyncResult.SetAsCompleted(result, false);
  267. }
  268. catch (Exception exp)
  269. {
  270. asyncResult.SetAsCompleted(exp, false);
  271. }
  272. });
  273. return asyncResult;
  274. }
  275. /// <summary>
  276. /// Ends an asynchronous operation of retrieving list of files in remote directory.
  277. /// </summary>
  278. /// <param name="asyncResult">The pending asynchronous SFTP request.</param>
  279. /// <returns>
  280. /// List of files
  281. /// </returns>
  282. public IEnumerable<SftpFile> EndListDirectory(IAsyncResult asyncResult)
  283. {
  284. var ar = asyncResult as SftpListDirectoryAsyncResult;
  285. if (ar == null || ar.EndInvokeCalled)
  286. 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.");
  287. // Wait for operation to complete, then return result or throw exception
  288. return ar.EndInvoke();
  289. }
  290. /// <summary>
  291. /// Gets reference to remote file or directory.
  292. /// </summary>
  293. /// <param name="path">The path.</param>
  294. /// <returns></returns>
  295. /// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception>
  296. public SftpFile Get(string path)
  297. {
  298. if (path == null)
  299. throw new ArgumentNullException("path");
  300. // Ensure that connection is established.
  301. this.EnsureConnection();
  302. var fullPath = this._sftpSession.GetCanonicalPath(path);
  303. var attributes = this._sftpSession.RequestLStat(fullPath);
  304. return new SftpFile(this._sftpSession, fullPath, attributes);
  305. }
  306. /// <summary>
  307. /// Checks whether file pr directory exists;
  308. /// </summary>
  309. /// <param name="path">The path.</param>
  310. /// <returns><c>true</c> if directory or file exists; otherwise <c>false</c>.</returns>
  311. /// <exception cref="ArgumentException"><paramref name="path"/> is null or contains whitespace characters.</exception>
  312. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  313. /// <exception cref="Renci.SshNet.Common.SftpPermissionDeniedException">Permission to perform the operation was denied by the remote host -or- a SSH command was denied by the server.</exception>
  314. /// <exception cref="Renci.SshNet.Common.SshException">A SSH error where <see cref="P:SshException.Message"/> is the message from the remote host.</exception>
  315. public bool Exists(string path)
  316. {
  317. if (string.IsNullOrWhiteSpace(path))
  318. throw new ArgumentException("path");
  319. // Ensure that connection is established.
  320. this.EnsureConnection();
  321. var fullPath = this._sftpSession.GetCanonicalPath(path);
  322. // Try to open as a file
  323. var handle = this._sftpSession.RequestOpen(fullPath, Flags.Read, true);
  324. if (handle == null)
  325. {
  326. handle = this._sftpSession.RequestOpenDir(fullPath, true);
  327. }
  328. if (handle == null)
  329. {
  330. return false;
  331. }
  332. else
  333. {
  334. this._sftpSession.RequestClose(handle);
  335. return true;
  336. }
  337. }
  338. /// <summary>
  339. /// Downloads remote file specified by the path into the stream.
  340. /// </summary>
  341. /// <param name="path">File to download.</param>
  342. /// <param name="output">Stream to write the file into.</param>
  343. /// <exception cref="ArgumentNullException"><paramref name="output"/> is null.</exception>
  344. /// <exception cref="ArgumentException"><paramref name="path"/> is null or contains whitespace characters.</exception>
  345. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  346. /// <exception cref="Renci.SshNet.Common.SftpPermissionDeniedException">Permission to perform the operation was denied by the remote host -or- a SSH command was denied by the server.</exception>
  347. /// <exception cref="Renci.SshNet.Common.SshException">A SSH error where <see cref="P:SshException.Message"/> is the message from the remote host.</exception>
  348. /// <remarks>Method calls made by this method to <paramref name="output"/>, may under certain conditions result in exceptions thrown by the stream.</remarks>
  349. public void DownloadFile(string path, Stream output)
  350. {
  351. this.InternalDownloadFile(path, output, null);
  352. }
  353. /// <summary>
  354. /// Begins an asynchronous file downloading into the stream.
  355. /// </summary>
  356. /// <param name="path">The path.</param>
  357. /// <param name="output">The output.</param>
  358. /// <param name="asyncCallback">The method to be called when the asynchronous write operation is completed.</param>
  359. /// <param name="state">A user-provided object that distinguishes this particular asynchronous write request from other requests.</param>
  360. /// <returns>An <see cref="IAsyncResult"/> that references the asynchronous operation.</returns>
  361. /// <exception cref="ArgumentNullException"><paramref name="output"/> is null.</exception>
  362. /// <exception cref="ArgumentException"><paramref name="path"/> is null or contains whitespace characters.</exception>
  363. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  364. /// <exception cref="Renci.SshNet.Common.SftpPermissionDeniedException">Permission to perform the operation was denied by the remote host -or- a SSH command was denied by the server.</exception>
  365. /// <exception cref="Renci.SshNet.Common.SshException">A SSH error where <see cref="P:SshException.Message"/> is the message from the remote host.</exception>
  366. /// <remarks>Method calls made by this method to <paramref name="output"/>, may under certain conditions result in exceptions thrown by the stream.</remarks>
  367. public IAsyncResult BeginDownloadFile(string path, Stream output, AsyncCallback asyncCallback, object state)
  368. {
  369. if (string.IsNullOrWhiteSpace(path))
  370. throw new ArgumentException("path");
  371. if (output == null)
  372. throw new ArgumentNullException("output");
  373. // Ensure that connection is established.
  374. this.EnsureConnection();
  375. var asyncResult = new SftpDownloadAsyncResult(asyncCallback, state);
  376. this.ExecuteThread(() =>
  377. {
  378. try
  379. {
  380. this.InternalDownloadFile(path, output, asyncResult);
  381. asyncResult.SetAsCompleted(null, false);
  382. }
  383. catch (Exception exp)
  384. {
  385. asyncResult.SetAsCompleted(exp, false);
  386. }
  387. });
  388. return asyncResult;
  389. }
  390. /// <summary>
  391. /// Ends an asynchronous file downloading into the stream.
  392. /// </summary>
  393. /// <param name="asyncResult">The pending asynchronous SFTP request.</param>
  394. /// <exception cref="ArgumentException">Either the IAsyncResult object (<paramref name="asyncResult"/>) did not come from the corresponding async method on this type, or EndExecute was called multiple times with the same IAsyncResult.</exception>
  395. public void EndDownloadFile(IAsyncResult asyncResult)
  396. {
  397. var ar = asyncResult as SftpDownloadAsyncResult;
  398. if (ar == null || ar.EndInvokeCalled)
  399. 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.");
  400. // Wait for operation to complete, then return result or throw exception
  401. ar.EndInvoke();
  402. }
  403. /// <summary>
  404. /// Uploads stream into remote file..
  405. /// </summary>
  406. /// <param name="input">Data input stream.</param>
  407. /// <param name="path">Remote file path.</param>
  408. /// <exception cref="ArgumentNullException"><paramref name="input"/> is null.</exception>
  409. /// <exception cref="ArgumentException"><paramref name="path"/> is null or contains whitespace characters.</exception>
  410. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  411. /// <exception cref="Renci.SshNet.Common.SftpPermissionDeniedException">Permission to upload the file was denied by the remote host -or- a SSH command was denied by the server.</exception>
  412. /// <exception cref="Renci.SshNet.Common.SshException">A SSH error where <see cref="P:SshException.Message"/> is the message from the remote host.</exception>
  413. /// <remarks>Method calls made by this method to <paramref name="input"/>, may under certain conditions result in exceptions thrown by the stream.</remarks>
  414. public void UploadFile(Stream input, string path)
  415. {
  416. this.InternalUploadFile(input, path, null);
  417. }
  418. /// <summary>
  419. /// Begins an asynchronous uploading the steam into remote file.
  420. /// </summary>
  421. /// <param name="input">Data input stream.</param>
  422. /// <param name="path">Remote file path.</param>
  423. /// <param name="asyncCallback">The method to be called when the asynchronous write operation is completed.</param>
  424. /// <param name="state">A user-provided object that distinguishes this particular asynchronous write request from other requests.</param>
  425. /// <returns>An <see cref="IAsyncResult"/> that references the asynchronous operation.</returns>
  426. /// <exception cref="ArgumentNullException"><paramref name="input"/> is null.</exception>
  427. /// <exception cref="ArgumentException"><paramref name="path"/> is null or contains whitespace characters.</exception>
  428. /// <exception cref="SshConnectionException">Client is not connected.</exception>
  429. /// <exception cref="Renci.SshNet.Common.SftpPermissionDeniedException">Permission to list the contents of the directory was denied by the remote host -or- a SSH command was denied by the server.</exception>
  430. /// <exception cref="Renci.SshNet.Common.SshException">A SSH error where <see cref="P:SshException.Message"/> is the message from the remote host.</exception>
  431. /// <remarks>Method calls made by this method to <paramref name="input"/>, may under certain conditions result in exceptions thrown by the stream.</remarks>
  432. public IAsyncResult BeginUploadFile(Stream input, string path, AsyncCallback asyncCallback, object state)
  433. {
  434. if (input == null)
  435. throw new ArgumentNullException("input");
  436. if (string.IsNullOrWhiteSpace(path))
  437. throw new ArgumentException("path");
  438. // Ensure that connection is established.
  439. this.EnsureConnection();
  440. var asyncResult = new SftpUploadAsyncResult(asyncCallback, state);
  441. this.ExecuteThread(() =>
  442. {
  443. try
  444. {
  445. this.InternalUploadFile(input, path, asyncResult);
  446. asyncResult.SetAsCompleted(null, false);
  447. }
  448. catch (Exception exp)
  449. {
  450. asyncResult.SetAsCompleted(exp, false);
  451. }
  452. });
  453. return asyncResult;
  454. }
  455. /// <summary>
  456. /// Ends an asynchronous uploading the steam into remote file.
  457. /// </summary>
  458. /// <param name="asyncResult">The pending asynchronous SFTP request.</param>
  459. /// <exception cref="ArgumentException">Either the IAsyncResult object (<paramref name="asyncResult"/>) did not come from the corresponding async method on this type, or EndExecute was called multiple times with the same IAsyncResult.</exception>
  460. public void EndUploadFile(IAsyncResult asyncResult)
  461. {
  462. var ar = asyncResult as SftpUploadAsyncResult;
  463. if (ar == null || ar.EndInvokeCalled)
  464. 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.");
  465. // Wait for operation to complete, then return result or throw exception
  466. ar.EndInvoke();
  467. }
  468. #region File Methods
  469. /// <summary>
  470. /// Appends lines to a file, and then closes the file.
  471. /// </summary>
  472. /// <param name="path">The file to append the lines to. The file is created if it does not already exist.</param>
  473. /// <param name="contents">The lines to append to the file.</param>
  474. public void AppendAllLines(string path, IEnumerable<string> contents)
  475. {
  476. if (contents == null)
  477. throw new ArgumentNullException("contents");
  478. using (var stream = this.AppendText(path))
  479. {
  480. foreach (var line in contents)
  481. {
  482. stream.WriteLine(line);
  483. }
  484. }
  485. }
  486. /// <summary>
  487. /// Appends lines to a file by using a specified encoding, and then closes the file.
  488. /// </summary>
  489. /// <param name="path">The file to append the lines to. The file is created if it does not already exist.</param>
  490. /// <param name="contents">The lines to append to the file.</param>
  491. /// <param name="encoding">The character encoding to use.</param>
  492. public void AppendAllLines(string path, IEnumerable<string> contents, Encoding encoding)
  493. {
  494. if (contents == null)
  495. throw new ArgumentNullException("contents");
  496. using (var stream = this.AppendText(path, encoding))
  497. {
  498. foreach (var line in contents)
  499. {
  500. stream.WriteLine(line);
  501. }
  502. }
  503. }
  504. /// <summary>
  505. /// Opens a file, appends the specified string to the file, and then closes the file.
  506. /// If the file does not exist, this method creates a file, writes the specified string to the file, then closes the file.
  507. /// </summary>
  508. /// <param name="path">The file to append the specified string to.</param>
  509. /// <param name="contents">The string to append to the file.</param>
  510. public void AppendAllText(string path, string contents)
  511. {
  512. using (var stream = this.AppendText(path))
  513. {
  514. stream.Write(contents);
  515. }
  516. }
  517. /// <summary>
  518. /// Opens a file, appends the specified string to the file, and then closes the file.
  519. /// If the file does not exist, this method creates a file, writes the specified string to the file, then closes the file.
  520. /// </summary>
  521. /// <param name="path">The file to append the specified string to.</param>
  522. /// <param name="contents">The string to append to the file.</param>
  523. /// <param name="encoding">The character encoding to use.</param>
  524. public void AppendAllText(string path, string contents, Encoding encoding)
  525. {
  526. using (var stream = this.AppendText(path, encoding))
  527. {
  528. stream.Write(contents);
  529. }
  530. }
  531. /// <summary>
  532. /// Creates a <see cref="System.IO.StreamWriter"/> that appends UTF-8 encoded text to an existing file.
  533. /// </summary>
  534. /// <param name="path">The path to the file to append to.</param>
  535. /// <returns>A StreamWriter that appends UTF-8 encoded text to an existing file.</returns>
  536. public StreamWriter AppendText(string path)
  537. {
  538. return this.AppendText(path, Encoding.UTF8);
  539. }
  540. /// <summary>
  541. /// Creates a <see cref="System.IO.StreamWriter"/> that appends UTF-8 encoded text to an existing file.
  542. /// </summary>
  543. /// <param name="path">The path to the file to append to.</param>
  544. /// <param name="encoding">The character encoding to use.</param>
  545. /// <returns>
  546. /// A StreamWriter that appends UTF-8 encoded text to an existing file.
  547. /// </returns>
  548. public StreamWriter AppendText(string path, Encoding encoding)
  549. {
  550. if (encoding == null)
  551. throw new ArgumentNullException("encoding");
  552. return new StreamWriter(new SftpFileStream(this._sftpSession, path, FileMode.Append, FileAccess.Write), encoding);
  553. }
  554. /// <summary>
  555. /// Creates or overwrites a file in the specified path.
  556. /// </summary>
  557. /// <param name="path">The path and name of the file to create.</param>
  558. /// <returns>A <see cref="SftpFileStream"/> that provides read/write access to the file specified in path</returns>
  559. public SftpFileStream Create(string path)
  560. {
  561. return new SftpFileStream(this._sftpSession, path, FileMode.Create, FileAccess.ReadWrite);
  562. }
  563. /// <summary>
  564. /// Creates or overwrites the specified file.
  565. /// </summary>
  566. /// <param name="path">The path and name of the file to create.</param>
  567. /// <param name="bufferSize">The number of bytes buffered for reads and writes to the file.</param>
  568. /// <returns>A <see cref="SftpFileStream"/> that provides read/write access to the file specified in path</returns>
  569. public SftpFileStream Create(string path, int bufferSize)
  570. {
  571. return new SftpFileStream(this._sftpSession, path, FileMode.Create, FileAccess.ReadWrite, bufferSize);
  572. }
  573. /// <summary>
  574. /// Creates or opens a file for writing UTF-8 encoded text.
  575. /// </summary>
  576. /// <param name="path">The file to be opened for writing.</param>
  577. /// <returns>A <see cref="System.IO.StreamWriter"/> that writes to the specified file using UTF-8 encoding.</returns>
  578. public StreamWriter CreateText(string path)
  579. {
  580. return new StreamWriter(this.OpenWrite(path), Encoding.UTF8);
  581. }
  582. /// <summary>
  583. /// Creates or opens a file for writing UTF-8 encoded text.
  584. /// </summary>
  585. /// <param name="path">The file to be opened for writing.</param>
  586. /// <param name="encoding">The character encoding to use.</param>
  587. /// <returns> A <see cref="System.IO.StreamWriter"/> that writes to the specified file using UTF-8 encoding. </returns>
  588. public StreamWriter CreateText(string path, Encoding encoding)
  589. {
  590. return new StreamWriter(this.OpenWrite(path), encoding);
  591. }
  592. /// <summary>
  593. /// Deletes the specified file or directory. An exception is not thrown if the specified file does not exist.
  594. /// </summary>
  595. /// <param name="path">The name of the file or directory to be deleted. Wildcard characters are not supported.</param>
  596. public void Delete(string path)
  597. {
  598. var file = this.Get(path);
  599. file.Delete();
  600. }
  601. /// <summary>
  602. /// Returns the date and time the specified file or directory was last accessed.
  603. /// </summary>
  604. /// <param name="path">The file or directory for which to obtain access date and time information.</param>
  605. /// <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>
  606. public DateTime GetLastAccessTime(string path)
  607. {
  608. var file = this.Get(path);
  609. return file.LastAccessTime;
  610. }
  611. /// <summary>
  612. /// Returns the date and time, in coordinated universal time (UTC), that the specified file or directory was last accessed.
  613. /// </summary>
  614. /// <param name="path">The file or directory for which to obtain access date and time information.</param>
  615. /// <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>
  616. public DateTime GetLastAccessTimeUtc(string path)
  617. {
  618. var file = this.Get(path);
  619. return file.LastAccessTime.ToUniversalTime();
  620. }
  621. /// <summary>
  622. /// Returns the date and time the specified file or directory was last written to.
  623. /// </summary>
  624. /// <param name="path">The file or directory for which to obtain write date and time information.</param>
  625. /// <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>
  626. public DateTime GetLastWriteTime(string path)
  627. {
  628. var file = this.Get(path);
  629. return file.LastWriteTime;
  630. }
  631. /// <summary>
  632. /// Returns the date and time, in coordinated universal time (UTC), that the specified file or directory was last written to.
  633. /// </summary>
  634. /// <param name="path">The file or directory for which to obtain write date and time information.</param>
  635. /// <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>
  636. public DateTime GetLastWriteTimeUtc(string path)
  637. {
  638. var file = this.Get(path);
  639. return file.LastWriteTime.ToUniversalTime();
  640. }
  641. /// <summary>
  642. /// Opens a <see cref="SftpFileStream"/> on the specified path with read/write access.
  643. /// </summary>
  644. /// <param name="path">The file to open.</param>
  645. /// <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>
  646. /// <returns>An unshared <see cref="SftpFileStream"/> that provides access to the specified file, with the specified mode and access.</returns>
  647. public SftpFileStream Open(string path, FileMode mode)
  648. {
  649. return new SftpFileStream(this._sftpSession, path, mode, FileAccess.ReadWrite);
  650. }
  651. /// <summary>
  652. /// Opens a <see cref="SftpFileStream"/> on the specified path, with the specified mode and access.
  653. /// </summary>
  654. /// <param name="path">The file to open.</param>
  655. /// <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>
  656. /// <param name="access">A <see cref="System.IO.FileAccess"/> value that specifies the operations that can be performed on the file.</param>
  657. /// <returns>An unshared <see cref="SftpFileStream"/> that provides access to the specified file, with the specified mode and access.</returns>
  658. public SftpFileStream Open(string path, FileMode mode, FileAccess access)
  659. {
  660. return new SftpFileStream(this._sftpSession, path, mode, access);
  661. }
  662. /// <summary>
  663. /// Opens an existing file for reading.
  664. /// </summary>
  665. /// <param name="path">The file to be opened for reading.</param>
  666. /// <returns>A read-only System.IO.FileStream on the specified path.</returns>
  667. public SftpFileStream OpenRead(string path)
  668. {
  669. return new SftpFileStream(this._sftpSession, path, FileMode.Open, FileAccess.Read);
  670. }
  671. /// <summary>
  672. /// Opens an existing UTF-8 encoded text file for reading.
  673. /// </summary>
  674. /// <param name="path">The file to be opened for reading.</param>
  675. /// <returns>A <see cref="System.IO.StreamReader"/> on the specified path.</returns>
  676. public StreamReader OpenText(string path)
  677. {
  678. return new StreamReader(this.OpenRead(path), Encoding.UTF8);
  679. }
  680. /// <summary>
  681. /// Opens an existing file for writing.
  682. /// </summary>
  683. /// <param name="path">The file to be opened for writing.</param>
  684. /// <returns>An unshared <see cref="SftpFileStream"/> object on the specified path with <see cref="System.IO.FileAccess.Write"/> access.</returns>
  685. public SftpFileStream OpenWrite(string path)
  686. {
  687. return new SftpFileStream(this._sftpSession, path, FileMode.OpenOrCreate, FileAccess.Write);
  688. }
  689. /// <summary>
  690. /// Opens a binary file, reads the contents of the file into a byte array, and then closes the file.
  691. /// </summary>
  692. /// <param name="path">The file to open for reading.</param>
  693. /// <returns>A byte array containing the contents of the file.</returns>
  694. public byte[] ReadAllBytes(string path)
  695. {
  696. using (var stream = this.OpenRead(path))
  697. {
  698. var buffer = new byte[stream.Length];
  699. stream.Read(buffer, 0, buffer.Length);
  700. return buffer;
  701. }
  702. }
  703. /// <summary>
  704. /// Opens a text file, reads all lines of the file, and then closes the file.
  705. /// </summary>
  706. /// <param name="path">The file to open for reading.</param>
  707. /// <returns>A string array containing all lines of the file.</returns>
  708. public string[] ReadAllLines(string path)
  709. {
  710. return this.ReadAllLines(path, Encoding.UTF8);
  711. }
  712. /// <summary>
  713. /// Opens a file, reads all lines of the file with the specified encoding, and then closes the file.
  714. /// </summary>
  715. /// <param name="path">The file to open for reading.</param>
  716. /// <param name="encoding">The encoding applied to the contents of the file.</param>
  717. /// <returns>A string array containing all lines of the file.</returns>
  718. public string[] ReadAllLines(string path, Encoding encoding)
  719. {
  720. var lines = new List<string>();
  721. using (var stream = new StreamReader(this.OpenRead(path), encoding))
  722. {
  723. while (!stream.EndOfStream)
  724. {
  725. lines.Add(stream.ReadLine());
  726. }
  727. }
  728. return lines.ToArray();
  729. }
  730. /// <summary>
  731. /// Opens a text file, reads all lines of the file, and then closes the file.
  732. /// </summary>
  733. /// <param name="path">The file to open for reading.</param>
  734. /// <returns>A string containing all lines of the file.</returns>
  735. public string ReadAllText(string path)
  736. {
  737. return this.ReadAllText(path, Encoding.UTF8);
  738. }
  739. /// <summary>
  740. /// Opens a file, reads all lines of the file with the specified encoding, and then closes the file.
  741. /// </summary>
  742. /// <param name="path">The file to open for reading.</param>
  743. /// <param name="encoding">The encoding applied to the contents of the file.</param>
  744. /// <returns>A string containing all lines of the file.</returns>
  745. public string ReadAllText(string path, Encoding encoding)
  746. {
  747. var lines = new List<string>();
  748. using (var stream = new StreamReader(this.OpenRead(path), encoding))
  749. {
  750. return stream.ReadToEnd();
  751. }
  752. }
  753. /// <summary>
  754. /// Reads the lines of a file.
  755. /// </summary>
  756. /// <param name="path">The file to read.</param>
  757. /// <returns>The lines of the file.</returns>
  758. public IEnumerable<string> ReadLines(string path)
  759. {
  760. return this.ReadAllLines(path);
  761. }
  762. /// <summary>
  763. /// Read the lines of a file that has a specified encoding.
  764. /// </summary>
  765. /// <param name="path">The file to read.</param>
  766. /// <param name="encoding">The encoding that is applied to the contents of the file.</param>
  767. /// <returns>The lines of the file.</returns>
  768. public IEnumerable<string> ReadLines(string path, Encoding encoding)
  769. {
  770. return this.ReadAllLines(path, encoding);
  771. }
  772. /// <summary>
  773. /// Sets the date and time the specified file was last accessed.
  774. /// </summary>
  775. /// <param name="path">The file for which to set the access date and time information.</param>
  776. /// <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>
  777. public void SetLastAccessTime(string path, DateTime lastAccessTime)
  778. {
  779. throw new NotImplementedException();
  780. }
  781. /// <summary>
  782. /// Sets the date and time, in coordinated universal time (UTC), that the specified file was last accessed.
  783. /// </summary>
  784. /// <param name="path">The file for which to set the access date and time information.</param>
  785. /// <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>
  786. public void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc)
  787. {
  788. throw new NotImplementedException();
  789. }
  790. /// <summary>
  791. /// Sets the date and time that the specified file was last written to.
  792. /// </summary>
  793. /// <param name="path">The file for which to set the date and time information.</param>
  794. /// <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>
  795. public void SetLastWriteTime(string path, DateTime lastWriteTime)
  796. {
  797. throw new NotImplementedException();
  798. }
  799. /// <summary>
  800. /// Sets the date and time, in coordinated universal time (UTC), that the specified file was last written to.
  801. /// </summary>
  802. /// <param name="path">The file for which to set the date and time information.</param>
  803. /// <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>
  804. public void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc)
  805. {
  806. throw new NotImplementedException();
  807. }
  808. /// <summary>
  809. /// 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.
  810. /// </summary>
  811. /// <param name="path">The file to write to.</param>
  812. /// <param name="bytes">The bytes to write to the file.</param>
  813. public void WriteAllBytes(string path, byte[] bytes)
  814. {
  815. using (var stream = this.OpenWrite(path))
  816. {
  817. stream.Write(bytes, 0, bytes.Length);
  818. }
  819. }
  820. /// <summary>
  821. /// Creates a new file, writes a collection of strings to the file, and then closes the file.
  822. /// </summary>
  823. /// <param name="path">The file to write to.</param>
  824. /// <param name="contents">The lines to write to the file.</param>
  825. public void WriteAllLines(string path, IEnumerable<string> contents)
  826. {
  827. this.WriteAllLines(path, contents, Encoding.UTF8);
  828. }
  829. /// <summary>
  830. /// Creates a new file, write the specified string array to the file, and then closes the file.
  831. /// </summary>
  832. /// <param name="path">The file to write to.</param>
  833. /// <param name="contents">The string array to write to the file.</param>
  834. public void WriteAllLines(string path, string[] contents)
  835. {
  836. this.WriteAllLines(path, contents, Encoding.UTF8);
  837. }
  838. /// <summary>
  839. /// Creates a new file by using the specified encoding, writes a collection of strings to the file, and then closes the file.
  840. /// </summary>
  841. /// <param name="path">The file to write to.</param>
  842. /// <param name="contents">The lines to write to the file.</param>
  843. /// <param name="encoding">The character encoding to use.</param>
  844. public void WriteAllLines(string path, IEnumerable<string> contents, Encoding encoding)
  845. {
  846. using (var stream = this.CreateText(path, encoding))
  847. {
  848. foreach (var line in contents)
  849. {
  850. stream.WriteLine(line);
  851. }
  852. }
  853. }
  854. /// <summary>
  855. /// Creates a new file, writes the specified string array to the file by using the specified encoding, and then closes the file.
  856. /// </summary>
  857. /// <param name="path">The file to write to.</param>
  858. /// <param name="contents">The string array to write to the file.</param>
  859. /// <param name="encoding">An <see cref="System.Text.Encoding"/> object that represents the character encoding applied to the string array.</param>
  860. public void WriteAllLines(string path, string[] contents, Encoding encoding)
  861. {
  862. using (var stream = this.CreateText(path, encoding))
  863. {
  864. foreach (var line in contents)
  865. {
  866. stream.WriteLine(line);
  867. }
  868. }
  869. }
  870. /// <summary>
  871. /// 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.
  872. /// </summary>
  873. /// <param name="path">The file to write to.</param>
  874. /// <param name="contents">The string to write to the file.</param>
  875. public void WriteAllText(string path, string contents)
  876. {
  877. using (var stream = this.CreateText(path))
  878. {
  879. stream.Write(contents);
  880. }
  881. }
  882. /// <summary>
  883. /// 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.
  884. /// </summary>
  885. /// <param name="path">The file to write to.</param>
  886. /// <param name="contents">The string to write to the file.</param>
  887. /// <param name="encoding">The encoding to apply to the string.</param>
  888. public void WriteAllText(string path, string contents, Encoding encoding)
  889. {
  890. using (var stream = this.CreateText(path, encoding))
  891. {
  892. stream.Write(contents);
  893. }
  894. }
  895. /// <summary>
  896. /// Gets the <see cref="SftpFileAttributes"/> of the file on the path.
  897. /// </summary>
  898. /// <param name="path">The path to the file.</param>
  899. /// <returns>The <see cref="SftpFileAttributes"/> of the file on the path.</returns>
  900. public SftpFileAttributes GetAttributes(string path)
  901. {
  902. var fullPath = this._sftpSession.GetCanonicalPath(path);
  903. return this._sftpSession.RequestLStat(fullPath);
  904. }
  905. /// <summary>
  906. /// Sets the specified <see cref="SftpFileAttributes"/> of the file on the specified path.
  907. /// </summary>
  908. /// <param name="path">The path to the file.</param>
  909. /// <param name="fileAttributes">The desired <see cref="SftpFileAttributes"/>.</param>
  910. public void SetAttributes(string path, SftpFileAttributes fileAttributes)
  911. {
  912. var fullPath = this._sftpSession.GetCanonicalPath(path);
  913. this._sftpSession.RequestSetStat(fullPath, fileAttributes);
  914. }
  915. //public FileSecurity GetAccessControl(string path);
  916. //public FileSecurity GetAccessControl(string path, AccessControlSections includeSections);
  917. //public DateTime GetCreationTime(string path);
  918. //public DateTime GetCreationTimeUtc(string path);
  919. //public void SetAccessControl(string path, FileSecurity fileSecurity);
  920. //public void SetCreationTime(string path, DateTime creationTime);
  921. //public void SetCreationTimeUtc(string path, DateTime creationTimeUtc);
  922. #endregion
  923. private IEnumerable<SftpFile> InternalListDirectory(string path, SftpListDirectoryAsyncResult asynchResult)
  924. {
  925. if (path == null)
  926. throw new ArgumentNullException("path");
  927. // Ensure that connection is established.
  928. this.EnsureConnection();
  929. var fullPath = this._sftpSession.GetCanonicalPath(path);
  930. var handle = this._sftpSession.RequestOpenDir(fullPath);
  931. var basePath = fullPath;
  932. if (!basePath.EndsWith("/"))
  933. basePath = string.Format("{0}/", fullPath);
  934. var result = new List<SftpFile>();
  935. var files = this._sftpSession.RequestReadDir(handle);
  936. while (files != null)
  937. {
  938. result.AddRange(from f in files
  939. select new SftpFile(this._sftpSession, string.Format(CultureInfo.InvariantCulture, "{0}{1}", basePath, f.Key), f.Value));
  940. if (asynchResult != null)
  941. {
  942. asynchResult.Update(result.Count);
  943. }
  944. files = this._sftpSession.RequestReadDir(handle);
  945. }
  946. return result;
  947. }
  948. private void InternalDownloadFile(string path, Stream output, SftpDownloadAsyncResult asynchResult)
  949. {
  950. if (output == null)
  951. throw new ArgumentNullException("output");
  952. if (string.IsNullOrWhiteSpace(path))
  953. throw new ArgumentException("path");
  954. // Ensure that connection is established.
  955. this.EnsureConnection();
  956. var fullPath = this._sftpSession.GetCanonicalPath(path);
  957. var handle = this._sftpSession.RequestOpen(fullPath, Flags.Read);
  958. ulong offset = 0;
  959. var data = this._sftpSession.RequestRead(handle, offset, this.BufferSize);
  960. // Read data while available
  961. while (data != null)
  962. {
  963. output.Write(data, 0, data.Length);
  964. output.Flush();
  965. offset += (ulong)data.Length;
  966. // Call callback to report number of bytes read
  967. if (asynchResult != null)
  968. {
  969. asynchResult.Update(offset);
  970. }
  971. data = this._sftpSession.RequestRead(handle, offset, this.BufferSize);
  972. }
  973. this._sftpSession.RequestClose(handle);
  974. }
  975. private void InternalUploadFile(Stream input, string path, SftpUploadAsyncResult asynchResult)
  976. {
  977. if (input == null)
  978. throw new ArgumentNullException("input");
  979. if (string.IsNullOrWhiteSpace(path))
  980. throw new ArgumentException("path");
  981. // Ensure that connection is established.
  982. this.EnsureConnection();
  983. var fullPath = this._sftpSession.GetCanonicalPath(path);
  984. var handle = this._sftpSession.RequestOpen(fullPath, Flags.Write | Flags.CreateNewOrOpen | Flags.Truncate);
  985. ulong offset = 0;
  986. var buffer = new byte[this.BufferSize];
  987. var uploadCompleted = false;
  988. do
  989. {
  990. var bytesRead = input.Read(buffer, 0, buffer.Length);
  991. if (bytesRead < this.BufferSize)
  992. {
  993. var data = new byte[bytesRead];
  994. Array.Copy(buffer, data, bytesRead);
  995. this._sftpSession.RequestWrite(handle, offset, data);
  996. uploadCompleted = true;
  997. }
  998. else
  999. {
  1000. this._sftpSession.RequestWrite(handle, offset, buffer);
  1001. }
  1002. offset += (uint)bytesRead;
  1003. // Call callback to report number of bytes read
  1004. if (asynchResult != null)
  1005. {
  1006. asynchResult.Update(offset);
  1007. }
  1008. } while (!uploadCompleted);
  1009. this._sftpSession.RequestClose(handle);
  1010. }
  1011. partial void ExecuteThread(Action action);
  1012. /// <summary>
  1013. /// Called when client is connected to the server.
  1014. /// </summary>
  1015. protected override void OnConnected()
  1016. {
  1017. base.OnConnected();
  1018. this._sftpSession = new SftpSession(this.Session, this.OperationTimeout);
  1019. this._sftpSession.Connect();
  1020. // Resolve current running version
  1021. this.ProtocolVersion = this._sftpSession.ProtocolVersion;
  1022. }
  1023. /// <summary>
  1024. /// Called when client is disconnecting from the server.
  1025. /// </summary>
  1026. protected override void OnDisconnecting()
  1027. {
  1028. base.OnDisconnecting();
  1029. this._sftpSession.Disconnect();
  1030. }
  1031. /// <summary>
  1032. /// Releases unmanaged and - optionally - managed resources
  1033. /// </summary>
  1034. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged ResourceMessages.</param>
  1035. protected override void Dispose(bool disposing)
  1036. {
  1037. if (this._sftpSession != null)
  1038. {
  1039. this._sftpSession.Dispose();
  1040. this._sftpSession = null;
  1041. }
  1042. base.Dispose(disposing);
  1043. }
  1044. }
  1045. }