SftpClient.cs 92 KB

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