SftpClient.cs 75 KB

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