SftpClient.cs 62 KB

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