SftpClient.cs 69 KB

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