SftpClient.cs 95 KB

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