2
0

SftpFileStream.cs 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349
  1. using System;
  2. using System.Diagnostics.CodeAnalysis;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using Renci.SshNet.Common;
  8. namespace Renci.SshNet.Sftp
  9. {
  10. /// <summary>
  11. /// Exposes a <see cref="Stream"/> around a remote SFTP file, supporting both synchronous and asynchronous read and write operations.
  12. /// </summary>
  13. /// <threadsafety static="true" instance="false"/>
  14. #pragma warning disable IDE0079 // We intentionally want to suppress the below warning.
  15. [SuppressMessage("Performance", "CA1844: Provide memory-based overrides of async methods when subclassing 'Stream'", Justification = "TODO: This should be addressed in the future.")]
  16. #pragma warning restore IDE0079
  17. public class SftpFileStream : Stream
  18. {
  19. private readonly Lock _lock = new Lock();
  20. private readonly int _readBufferSize;
  21. private readonly int _writeBufferSize;
  22. // Internal state.
  23. private byte[] _handle;
  24. private ISftpSession _session;
  25. // Buffer information.
  26. private byte[] _readBuffer;
  27. private byte[] _writeBuffer;
  28. private int _bufferPosition;
  29. private int _bufferLen;
  30. private long _position;
  31. private bool _bufferOwnedByWrite;
  32. private bool _canRead;
  33. private bool _canSeek;
  34. private bool _canWrite;
  35. private TimeSpan _timeout;
  36. /// <summary>
  37. /// Gets a value indicating whether the current stream supports reading.
  38. /// </summary>
  39. /// <value>
  40. /// <see langword="true"/> if the stream supports reading; otherwise, <see langword="false"/>.
  41. /// </value>
  42. public override bool CanRead
  43. {
  44. get { return _canRead; }
  45. }
  46. /// <summary>
  47. /// Gets a value indicating whether the current stream supports seeking.
  48. /// </summary>
  49. /// <value>
  50. /// <see langword="true"/> if the stream supports seeking; otherwise, <see langword="false"/>.
  51. /// </value>
  52. public override bool CanSeek
  53. {
  54. get { return _canSeek; }
  55. }
  56. /// <summary>
  57. /// Gets a value indicating whether the current stream supports writing.
  58. /// </summary>
  59. /// <value>
  60. /// <see langword="true"/> if the stream supports writing; otherwise, <see langword="false"/>.
  61. /// </value>
  62. public override bool CanWrite
  63. {
  64. get { return _canWrite; }
  65. }
  66. /// <summary>
  67. /// Gets a value indicating whether timeout properties are usable for <see cref="SftpFileStream"/>.
  68. /// </summary>
  69. /// <value>
  70. /// <see langword="true"/> in all cases.
  71. /// </value>
  72. public override bool CanTimeout
  73. {
  74. get { return true; }
  75. }
  76. /// <summary>
  77. /// Gets the length in bytes of the stream.
  78. /// </summary>
  79. /// <value>A long value representing the length of the stream in bytes.</value>
  80. /// <exception cref="NotSupportedException">A class derived from Stream does not support seeking. </exception>
  81. /// <exception cref="ObjectDisposedException">Methods were called after the stream was closed. </exception>
  82. /// <exception cref="IOException">IO operation failed. </exception>
  83. public override long Length
  84. {
  85. get
  86. {
  87. // Lock down the file stream while we do this.
  88. lock (_lock)
  89. {
  90. CheckSessionIsOpen();
  91. if (!CanSeek)
  92. {
  93. throw new NotSupportedException("Seek operation is not supported.");
  94. }
  95. // Flush the write buffer, because it may
  96. // affect the length of the stream.
  97. if (_bufferOwnedByWrite)
  98. {
  99. FlushWriteBuffer();
  100. }
  101. // obtain file attributes
  102. var attributes = _session.RequestFStat(_handle, nullOnError: true);
  103. if (attributes != null)
  104. {
  105. return attributes.Size;
  106. }
  107. throw new IOException("Seek operation failed.");
  108. }
  109. }
  110. }
  111. /// <summary>
  112. /// Gets or sets the position within the current stream.
  113. /// </summary>
  114. /// <value>The current position within the stream.</value>
  115. /// <exception cref="IOException">An I/O error occurs. </exception>
  116. /// <exception cref="NotSupportedException">The stream does not support seeking. </exception>
  117. /// <exception cref="ObjectDisposedException">Methods were called after the stream was closed. </exception>
  118. public override long Position
  119. {
  120. get
  121. {
  122. CheckSessionIsOpen();
  123. if (!CanSeek)
  124. {
  125. throw new NotSupportedException("Seek operation not supported.");
  126. }
  127. return _position;
  128. }
  129. set
  130. {
  131. _ = Seek(value, SeekOrigin.Begin);
  132. }
  133. }
  134. /// <summary>
  135. /// Gets the name of the path that was used to construct the current <see cref="SftpFileStream"/>.
  136. /// </summary>
  137. /// <value>
  138. /// The name of the path that was used to construct the current <see cref="SftpFileStream"/>.
  139. /// </value>
  140. public string Name { get; private set; }
  141. /// <summary>
  142. /// Gets the operating system file handle for the file that the current <see cref="SftpFileStream"/> encapsulates.
  143. /// </summary>
  144. /// <value>
  145. /// The operating system file handle for the file that the current <see cref="SftpFileStream"/> encapsulates.
  146. /// </value>
  147. public virtual byte[] Handle
  148. {
  149. get
  150. {
  151. Flush();
  152. return _handle;
  153. }
  154. }
  155. /// <summary>
  156. /// Gets or sets the operation timeout.
  157. /// </summary>
  158. /// <value>
  159. /// The timeout.
  160. /// </value>
  161. public TimeSpan Timeout
  162. {
  163. get
  164. {
  165. return _timeout;
  166. }
  167. set
  168. {
  169. value.EnsureValidTimeout(nameof(Timeout));
  170. _timeout = value;
  171. }
  172. }
  173. private SftpFileStream(ISftpSession session, string path, FileAccess access, int bufferSize, byte[] handle, long position)
  174. {
  175. Timeout = TimeSpan.FromSeconds(30);
  176. Name = path;
  177. _session = session;
  178. _canRead = (access & FileAccess.Read) == FileAccess.Read;
  179. _canSeek = true;
  180. _canWrite = (access & FileAccess.Write) == FileAccess.Write;
  181. _handle = handle;
  182. /*
  183. * Instead of using the specified buffer size as is, we use it to calculate a buffer size
  184. * that ensures we always receive or send the max. number of bytes in a single SSH_FXP_READ
  185. * or SSH_FXP_WRITE message.
  186. */
  187. _readBufferSize = (int)session.CalculateOptimalReadLength((uint)bufferSize);
  188. _writeBufferSize = (int)session.CalculateOptimalWriteLength((uint)bufferSize, _handle);
  189. _position = position;
  190. }
  191. internal SftpFileStream(ISftpSession session, string path, FileMode mode, FileAccess access, int bufferSize)
  192. {
  193. if (session is null)
  194. {
  195. throw new SshConnectionException("Client not connected.");
  196. }
  197. ThrowHelper.ThrowIfNull(path);
  198. if (bufferSize <= 0)
  199. {
  200. throw new ArgumentOutOfRangeException(nameof(bufferSize), "Cannot be less than or equal to zero.");
  201. }
  202. Timeout = TimeSpan.FromSeconds(30);
  203. Name = path;
  204. // Initialize the object state.
  205. _session = session;
  206. _canRead = (access & FileAccess.Read) == FileAccess.Read;
  207. _canSeek = true;
  208. _canWrite = (access & FileAccess.Write) == FileAccess.Write;
  209. var flags = Flags.None;
  210. switch (access)
  211. {
  212. case FileAccess.Read:
  213. flags |= Flags.Read;
  214. break;
  215. case FileAccess.Write:
  216. flags |= Flags.Write;
  217. break;
  218. case FileAccess.ReadWrite:
  219. flags |= Flags.Read;
  220. flags |= Flags.Write;
  221. break;
  222. default:
  223. throw new ArgumentOutOfRangeException(nameof(access));
  224. }
  225. if ((access & FileAccess.Read) == FileAccess.Read && mode == FileMode.Append)
  226. {
  227. throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
  228. "{0} mode can be requested only when combined with write-only access.",
  229. mode.ToString("G")),
  230. nameof(mode));
  231. }
  232. if ((access & FileAccess.Write) != FileAccess.Write)
  233. {
  234. if (mode is FileMode.Create or FileMode.CreateNew or FileMode.Truncate or FileMode.Append)
  235. {
  236. throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
  237. "Combining {0}: {1} with {2}: {3} is invalid.",
  238. nameof(FileMode),
  239. mode,
  240. nameof(FileAccess),
  241. access),
  242. nameof(mode));
  243. }
  244. }
  245. switch (mode)
  246. {
  247. case FileMode.Append:
  248. flags |= Flags.Append | Flags.CreateNewOrOpen;
  249. break;
  250. case FileMode.Create:
  251. _handle = _session.RequestOpen(path, flags | Flags.Truncate, nullOnError: true);
  252. if (_handle is null)
  253. {
  254. flags |= Flags.CreateNew;
  255. }
  256. else
  257. {
  258. flags |= Flags.Truncate;
  259. }
  260. break;
  261. case FileMode.CreateNew:
  262. flags |= Flags.CreateNew;
  263. break;
  264. case FileMode.Open:
  265. break;
  266. case FileMode.OpenOrCreate:
  267. flags |= Flags.CreateNewOrOpen;
  268. break;
  269. case FileMode.Truncate:
  270. flags |= Flags.Truncate;
  271. break;
  272. default:
  273. throw new ArgumentOutOfRangeException(nameof(mode));
  274. }
  275. _handle ??= _session.RequestOpen(path, flags);
  276. /*
  277. * Instead of using the specified buffer size as is, we use it to calculate a buffer size
  278. * that ensures we always receive or send the max. number of bytes in a single SSH_FXP_READ
  279. * or SSH_FXP_WRITE message.
  280. */
  281. _readBufferSize = (int)session.CalculateOptimalReadLength((uint)bufferSize);
  282. _writeBufferSize = (int)session.CalculateOptimalWriteLength((uint)bufferSize, _handle);
  283. if (mode == FileMode.Append)
  284. {
  285. var attributes = _session.RequestFStat(_handle, nullOnError: false);
  286. _position = attributes.Size;
  287. }
  288. }
  289. internal static async Task<SftpFileStream> OpenAsync(ISftpSession session, string path, FileMode mode, FileAccess access, int bufferSize, CancellationToken cancellationToken)
  290. {
  291. if (session is null)
  292. {
  293. throw new SshConnectionException("Client not connected.");
  294. }
  295. ThrowHelper.ThrowIfNull(path);
  296. if (bufferSize <= 0)
  297. {
  298. throw new ArgumentOutOfRangeException(nameof(bufferSize), "Cannot be less than or equal to zero.");
  299. }
  300. var flags = Flags.None;
  301. switch (access)
  302. {
  303. case FileAccess.Read:
  304. flags |= Flags.Read;
  305. break;
  306. case FileAccess.Write:
  307. flags |= Flags.Write;
  308. break;
  309. case FileAccess.ReadWrite:
  310. flags |= Flags.Read;
  311. flags |= Flags.Write;
  312. break;
  313. default:
  314. throw new ArgumentOutOfRangeException(nameof(access));
  315. }
  316. if ((access & FileAccess.Read) == FileAccess.Read && mode == FileMode.Append)
  317. {
  318. throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
  319. "{0} mode can be requested only when combined with write-only access.",
  320. mode.ToString("G")),
  321. nameof(mode));
  322. }
  323. if ((access & FileAccess.Write) != FileAccess.Write)
  324. {
  325. if (mode is FileMode.Create or FileMode.CreateNew or FileMode.Truncate or FileMode.Append)
  326. {
  327. throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
  328. "Combining {0}: {1} with {2}: {3} is invalid.",
  329. nameof(FileMode),
  330. mode,
  331. nameof(FileAccess),
  332. access),
  333. nameof(mode));
  334. }
  335. }
  336. switch (mode)
  337. {
  338. case FileMode.Append:
  339. flags |= Flags.Append | Flags.CreateNewOrOpen;
  340. break;
  341. case FileMode.Create:
  342. flags |= Flags.CreateNewOrOpen | Flags.Truncate;
  343. break;
  344. case FileMode.CreateNew:
  345. flags |= Flags.CreateNew;
  346. break;
  347. case FileMode.Open:
  348. break;
  349. case FileMode.OpenOrCreate:
  350. flags |= Flags.CreateNewOrOpen;
  351. break;
  352. case FileMode.Truncate:
  353. flags |= Flags.Truncate;
  354. break;
  355. default:
  356. throw new ArgumentOutOfRangeException(nameof(mode));
  357. }
  358. var handle = await session.RequestOpenAsync(path, flags, cancellationToken).ConfigureAwait(false);
  359. long position = 0;
  360. if (mode == FileMode.Append)
  361. {
  362. try
  363. {
  364. var attributes = await session.RequestFStatAsync(handle, cancellationToken).ConfigureAwait(false);
  365. position = attributes.Size;
  366. }
  367. catch
  368. {
  369. try
  370. {
  371. await session.RequestCloseAsync(handle, cancellationToken).ConfigureAwait(false);
  372. }
  373. catch
  374. {
  375. // The original exception is presumably more informative, so we just ignore this one.
  376. }
  377. throw;
  378. }
  379. }
  380. return new SftpFileStream(session, path, access, bufferSize, handle, position);
  381. }
  382. /// <summary>
  383. /// Clears all buffers for this stream and causes any buffered data to be written to the file.
  384. /// </summary>
  385. /// <exception cref="IOException">An I/O error occurs. </exception>
  386. /// <exception cref="ObjectDisposedException">Stream is closed.</exception>
  387. public override void Flush()
  388. {
  389. lock (_lock)
  390. {
  391. CheckSessionIsOpen();
  392. if (_bufferOwnedByWrite)
  393. {
  394. FlushWriteBuffer();
  395. }
  396. else
  397. {
  398. FlushReadBuffer();
  399. }
  400. }
  401. }
  402. /// <summary>
  403. /// Asynchronously clears all buffers for this stream and causes any buffered data to be written to the file.
  404. /// </summary>
  405. /// <param name="cancellationToken">The <see cref="CancellationToken"/> to observe.</param>
  406. /// <returns>A <see cref="Task"/> that represents the asynchronous flush operation.</returns>
  407. /// <exception cref="IOException">An I/O error occurs. </exception>
  408. /// <exception cref="ObjectDisposedException">Stream is closed.</exception>
  409. public override Task FlushAsync(CancellationToken cancellationToken)
  410. {
  411. CheckSessionIsOpen();
  412. if (_bufferOwnedByWrite)
  413. {
  414. return FlushWriteBufferAsync(cancellationToken);
  415. }
  416. FlushReadBuffer();
  417. return Task.CompletedTask;
  418. }
  419. /// <summary>
  420. /// Reads a sequence of bytes from the current stream and advances the position within the stream by the
  421. /// number of bytes read.
  422. /// </summary>
  423. /// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between <paramref name="offset"/> and (<paramref name="offset"/> + <paramref name="count"/> - 1) replaced by the bytes read from the current source.</param>
  424. /// <param name="offset">The zero-based byte offset in <paramref name="buffer"/> at which to begin storing the data read from the current stream.</param>
  425. /// <param name="count">The maximum number of bytes to be read from the current stream.</param>
  426. /// <returns>
  427. /// The total number of bytes read into the buffer. This can be less than the number of bytes requested
  428. /// if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.
  429. /// </returns>
  430. /// <exception cref="ArgumentException">The sum of <paramref name="offset"/> and <paramref name="count"/> is larger than the buffer length.</exception>
  431. /// <exception cref="ArgumentNullException"><paramref name="buffer"/> is <see langword="null"/>. </exception>
  432. /// <exception cref="ArgumentOutOfRangeException"><paramref name="offset"/> or <paramref name="count"/> is negative.</exception>
  433. /// <exception cref="IOException">An I/O error occurs. </exception>
  434. /// <exception cref="NotSupportedException">The stream does not support reading. </exception>
  435. /// <exception cref="ObjectDisposedException">Methods were called after the stream was closed. </exception>
  436. /// <remarks>
  437. /// <para>
  438. /// This method attempts to read up to <paramref name="count"/> bytes. This either from the buffer, from the
  439. /// server (using one or more <c>SSH_FXP_READ</c> requests) or using a combination of both.
  440. /// </para>
  441. /// <para>
  442. /// The read loop is interrupted when either <paramref name="count"/> bytes are read, the server returns zero
  443. /// bytes (EOF) or less bytes than the read buffer size.
  444. /// </para>
  445. /// <para>
  446. /// When a server returns less number of bytes than the read buffer size, this <c>may</c> indicate that EOF has
  447. /// been reached. A subsequent (<c>SSH_FXP_READ</c>) server request is necessary to make sure EOF has effectively
  448. /// been reached. Breaking out of the read loop avoids reading from the server twice to determine EOF: once in
  449. /// the read loop, and once upon the next <see cref="Read"/> or <see cref="ReadByte"/> invocation.
  450. /// </para>
  451. /// </remarks>
  452. public override int Read(byte[] buffer, int offset, int count)
  453. {
  454. var readLen = 0;
  455. ThrowHelper.ThrowIfNull(buffer);
  456. #if NET8_0_OR_GREATER
  457. ArgumentOutOfRangeException.ThrowIfNegative(offset);
  458. ArgumentOutOfRangeException.ThrowIfNegative(count);
  459. #else
  460. if (offset < 0)
  461. {
  462. throw new ArgumentOutOfRangeException(nameof(offset));
  463. }
  464. if (count < 0)
  465. {
  466. throw new ArgumentOutOfRangeException(nameof(count));
  467. }
  468. #endif
  469. if ((buffer.Length - offset) < count)
  470. {
  471. throw new ArgumentException("Invalid array range.");
  472. }
  473. // Lock down the file stream while we do this.
  474. lock (_lock)
  475. {
  476. CheckSessionIsOpen();
  477. // Set up for the read operation.
  478. SetupRead();
  479. // Read data into the caller's buffer.
  480. while (count > 0)
  481. {
  482. // How much data do we have available in the buffer?
  483. var bytesAvailableInBuffer = _bufferLen - _bufferPosition;
  484. if (bytesAvailableInBuffer <= 0)
  485. {
  486. var data = _session.RequestRead(_handle, (ulong)_position, (uint)_readBufferSize);
  487. if (data.Length == 0)
  488. {
  489. _bufferPosition = 0;
  490. _bufferLen = 0;
  491. break;
  492. }
  493. var bytesToWriteToCallerBuffer = count;
  494. if (bytesToWriteToCallerBuffer >= data.Length)
  495. {
  496. // write all data read to caller-provided buffer
  497. bytesToWriteToCallerBuffer = data.Length;
  498. // reset buffer since we will skip buffering
  499. _bufferPosition = 0;
  500. _bufferLen = 0;
  501. }
  502. else
  503. {
  504. // determine number of bytes that we should write into read buffer
  505. var bytesToWriteToReadBuffer = data.Length - bytesToWriteToCallerBuffer;
  506. // write remaining bytes to read buffer
  507. Buffer.BlockCopy(data, count, GetOrCreateReadBuffer(), 0, bytesToWriteToReadBuffer);
  508. // update position in read buffer
  509. _bufferPosition = 0;
  510. // update number of bytes in read buffer
  511. _bufferLen = bytesToWriteToReadBuffer;
  512. }
  513. // write bytes to caller-provided buffer
  514. Buffer.BlockCopy(data, 0, buffer, offset, bytesToWriteToCallerBuffer);
  515. // update stream position
  516. _position += bytesToWriteToCallerBuffer;
  517. // record total number of bytes read into caller-provided buffer
  518. readLen += bytesToWriteToCallerBuffer;
  519. // break out of the read loop when the server returned less than the request number of bytes
  520. // as that *may* indicate that we've reached EOF
  521. //
  522. // doing this avoids reading from server twice to determine EOF: once in the read loop, and
  523. // once upon the next Read or ReadByte invocation by the caller
  524. if (data.Length < _readBufferSize)
  525. {
  526. break;
  527. }
  528. // advance offset to start writing bytes into caller-provided buffer
  529. offset += bytesToWriteToCallerBuffer;
  530. // update number of bytes left to read into caller-provided buffer
  531. count -= bytesToWriteToCallerBuffer;
  532. }
  533. else
  534. {
  535. // limit the number of bytes to use from read buffer to the caller-request number of bytes
  536. if (bytesAvailableInBuffer > count)
  537. {
  538. bytesAvailableInBuffer = count;
  539. }
  540. // copy data from read buffer to the caller-provided buffer
  541. Buffer.BlockCopy(GetOrCreateReadBuffer(), _bufferPosition, buffer, offset, bytesAvailableInBuffer);
  542. // update position in read buffer
  543. _bufferPosition += bytesAvailableInBuffer;
  544. // update stream position
  545. _position += bytesAvailableInBuffer;
  546. // record total number of bytes read into caller-provided buffer
  547. readLen += bytesAvailableInBuffer;
  548. // advance offset to start writing bytes into caller-provided buffer
  549. offset += bytesAvailableInBuffer;
  550. // update number of bytes left to read
  551. count -= bytesAvailableInBuffer;
  552. }
  553. }
  554. }
  555. // return the number of bytes that were read to the caller.
  556. return readLen;
  557. }
  558. /// <summary>
  559. /// Asynchronously reads a sequence of bytes from the current stream and advances the position within the stream by the
  560. /// number of bytes read.
  561. /// </summary>
  562. /// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between <paramref name="offset"/> and (<paramref name="offset"/> + <paramref name="count"/> - 1) replaced by the bytes read from the current source.</param>
  563. /// <param name="offset">The zero-based byte offset in <paramref name="buffer"/> at which to begin storing the data read from the current stream.</param>
  564. /// <param name="count">The maximum number of bytes to be read from the current stream.</param>
  565. /// <param name="cancellationToken">The <see cref="CancellationToken" /> to observe.</param>
  566. /// <returns>A <see cref="Task" /> that represents the asynchronous read operation.</returns>
  567. public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
  568. {
  569. var readLen = 0;
  570. ThrowHelper.ThrowIfNull(buffer);
  571. #if NET8_0_OR_GREATER
  572. ArgumentOutOfRangeException.ThrowIfNegative(offset);
  573. ArgumentOutOfRangeException.ThrowIfNegative(count);
  574. #else
  575. if (offset < 0)
  576. {
  577. throw new ArgumentOutOfRangeException(nameof(offset));
  578. }
  579. if (count < 0)
  580. {
  581. throw new ArgumentOutOfRangeException(nameof(count));
  582. }
  583. #endif
  584. if ((buffer.Length - offset) < count)
  585. {
  586. throw new ArgumentException("Invalid array range.");
  587. }
  588. CheckSessionIsOpen();
  589. // Set up for the read operation.
  590. SetupRead();
  591. // Read data into the caller's buffer.
  592. while (count > 0)
  593. {
  594. // How much data do we have available in the buffer?
  595. var bytesAvailableInBuffer = _bufferLen - _bufferPosition;
  596. if (bytesAvailableInBuffer <= 0)
  597. {
  598. var data = await _session.RequestReadAsync(_handle, (ulong)_position, (uint)_readBufferSize, cancellationToken).ConfigureAwait(false);
  599. if (data.Length == 0)
  600. {
  601. _bufferPosition = 0;
  602. _bufferLen = 0;
  603. break;
  604. }
  605. var bytesToWriteToCallerBuffer = count;
  606. if (bytesToWriteToCallerBuffer >= data.Length)
  607. {
  608. // write all data read to caller-provided buffer
  609. bytesToWriteToCallerBuffer = data.Length;
  610. // reset buffer since we will skip buffering
  611. _bufferPosition = 0;
  612. _bufferLen = 0;
  613. }
  614. else
  615. {
  616. // determine number of bytes that we should write into read buffer
  617. var bytesToWriteToReadBuffer = data.Length - bytesToWriteToCallerBuffer;
  618. // write remaining bytes to read buffer
  619. Buffer.BlockCopy(data, count, GetOrCreateReadBuffer(), 0, bytesToWriteToReadBuffer);
  620. // update position in read buffer
  621. _bufferPosition = 0;
  622. // update number of bytes in read buffer
  623. _bufferLen = bytesToWriteToReadBuffer;
  624. }
  625. // write bytes to caller-provided buffer
  626. Buffer.BlockCopy(data, 0, buffer, offset, bytesToWriteToCallerBuffer);
  627. // update stream position
  628. _position += bytesToWriteToCallerBuffer;
  629. // record total number of bytes read into caller-provided buffer
  630. readLen += bytesToWriteToCallerBuffer;
  631. // break out of the read loop when the server returned less than the request number of bytes
  632. // as that *may* indicate that we've reached EOF
  633. //
  634. // doing this avoids reading from server twice to determine EOF: once in the read loop, and
  635. // once upon the next Read or ReadByte invocation by the caller
  636. if (data.Length < _readBufferSize)
  637. {
  638. break;
  639. }
  640. // advance offset to start writing bytes into caller-provided buffer
  641. offset += bytesToWriteToCallerBuffer;
  642. // update number of bytes left to read into caller-provided buffer
  643. count -= bytesToWriteToCallerBuffer;
  644. }
  645. else
  646. {
  647. // limit the number of bytes to use from read buffer to the caller-request number of bytes
  648. if (bytesAvailableInBuffer > count)
  649. {
  650. bytesAvailableInBuffer = count;
  651. }
  652. // copy data from read buffer to the caller-provided buffer
  653. Buffer.BlockCopy(GetOrCreateReadBuffer(), _bufferPosition, buffer, offset, bytesAvailableInBuffer);
  654. // update position in read buffer
  655. _bufferPosition += bytesAvailableInBuffer;
  656. // update stream position
  657. _position += bytesAvailableInBuffer;
  658. // record total number of bytes read into caller-provided buffer
  659. readLen += bytesAvailableInBuffer;
  660. // advance offset to start writing bytes into caller-provided buffer
  661. offset += bytesAvailableInBuffer;
  662. // update number of bytes left to read
  663. count -= bytesAvailableInBuffer;
  664. }
  665. }
  666. // return the number of bytes that were read to the caller.
  667. return readLen;
  668. }
  669. /// <summary>
  670. /// Reads a byte from the stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream.
  671. /// </summary>
  672. /// <returns>
  673. /// The unsigned byte cast to an <see cref="int"/>, or -1 if at the end of the stream.
  674. /// </returns>
  675. /// <exception cref="NotSupportedException">The stream does not support reading. </exception>
  676. /// <exception cref="ObjectDisposedException">Methods were called after the stream was closed. </exception>
  677. /// <exception cref="IOException">Read operation failed.</exception>
  678. public override int ReadByte()
  679. {
  680. // Lock down the file stream while we do this.
  681. lock (_lock)
  682. {
  683. CheckSessionIsOpen();
  684. // Setup the object for reading.
  685. SetupRead();
  686. byte[] readBuffer;
  687. // Read more data into the internal buffer if necessary.
  688. if (_bufferPosition >= _bufferLen)
  689. {
  690. var data = _session.RequestRead(_handle, (ulong)_position, (uint)_readBufferSize);
  691. if (data.Length == 0)
  692. {
  693. // We've reached EOF.
  694. return -1;
  695. }
  696. readBuffer = GetOrCreateReadBuffer();
  697. Buffer.BlockCopy(data, 0, readBuffer, 0, data.Length);
  698. _bufferPosition = 0;
  699. _bufferLen = data.Length;
  700. }
  701. else
  702. {
  703. readBuffer = GetOrCreateReadBuffer();
  704. }
  705. // Extract the next byte from the buffer.
  706. ++_position;
  707. return readBuffer[_bufferPosition++];
  708. }
  709. }
  710. /// <summary>
  711. /// Sets the position within the current stream.
  712. /// </summary>
  713. /// <param name="offset">A byte offset relative to the <paramref name="origin"/> parameter.</param>
  714. /// <param name="origin">A value of type <see cref="SeekOrigin"/> indicating the reference point used to obtain the new position.</param>
  715. /// <returns>
  716. /// The new position within the current stream.
  717. /// </returns>
  718. /// <exception cref="IOException">An I/O error occurs. </exception>
  719. /// <exception cref="NotSupportedException">The stream does not support seeking, such as if the stream is constructed from a pipe or console output. </exception>
  720. /// <exception cref="ObjectDisposedException">Methods were called after the stream was closed. </exception>
  721. public override long Seek(long offset, SeekOrigin origin)
  722. {
  723. long newPosn;
  724. // Lock down the file stream while we do this.
  725. lock (_lock)
  726. {
  727. CheckSessionIsOpen();
  728. if (!CanSeek)
  729. {
  730. throw new NotSupportedException("Seek is not supported.");
  731. }
  732. // Don't do anything if the position won't be moving.
  733. if (origin == SeekOrigin.Begin && offset == _position)
  734. {
  735. return offset;
  736. }
  737. if (origin == SeekOrigin.Current && offset == 0)
  738. {
  739. return _position;
  740. }
  741. // The behaviour depends upon the read/write mode.
  742. if (_bufferOwnedByWrite)
  743. {
  744. // Flush the write buffer and then seek.
  745. FlushWriteBuffer();
  746. }
  747. else
  748. {
  749. // Determine if the seek is to somewhere inside
  750. // the current read buffer bounds.
  751. if (origin == SeekOrigin.Begin)
  752. {
  753. newPosn = _position - _bufferPosition;
  754. if (offset >= newPosn && offset < (newPosn + _bufferLen))
  755. {
  756. _bufferPosition = (int)(offset - newPosn);
  757. _position = offset;
  758. return _position;
  759. }
  760. }
  761. else if (origin == SeekOrigin.Current)
  762. {
  763. newPosn = _position + offset;
  764. if (newPosn >= (_position - _bufferPosition) &&
  765. newPosn < (_position - _bufferPosition + _bufferLen))
  766. {
  767. _bufferPosition = (int)(newPosn - (_position - _bufferPosition));
  768. _position = newPosn;
  769. return _position;
  770. }
  771. }
  772. // Abandon the read buffer.
  773. _bufferPosition = 0;
  774. _bufferLen = 0;
  775. }
  776. // Seek to the new position.
  777. switch (origin)
  778. {
  779. case SeekOrigin.Begin:
  780. newPosn = offset;
  781. break;
  782. case SeekOrigin.Current:
  783. newPosn = _position + offset;
  784. break;
  785. case SeekOrigin.End:
  786. var attributes = _session.RequestFStat(_handle, nullOnError: false);
  787. newPosn = attributes.Size + offset;
  788. break;
  789. default:
  790. throw new ArgumentException("Invalid seek origin.", nameof(origin));
  791. }
  792. if (newPosn < 0)
  793. {
  794. throw new EndOfStreamException();
  795. }
  796. _position = newPosn;
  797. return _position;
  798. }
  799. }
  800. /// <summary>
  801. /// Sets the length of the current stream.
  802. /// </summary>
  803. /// <param name="value">The desired length of the current stream in bytes.</param>
  804. /// <exception cref="IOException">An I/O error occurs.</exception>
  805. /// <exception cref="NotSupportedException">The stream does not support both writing and seeking.</exception>
  806. /// <exception cref="ObjectDisposedException">Methods were called after the stream was closed.</exception>
  807. /// <exception cref="ArgumentOutOfRangeException"><paramref name="value"/> must be greater than zero.</exception>
  808. /// <remarks>
  809. /// <para>
  810. /// Buffers are first flushed.
  811. /// </para>
  812. /// <para>
  813. /// If the specified value is less than the current length of the stream, the stream is truncated and - if the
  814. /// current position is greater than the new length - the current position is moved to the last byte of the stream.
  815. /// </para>
  816. /// <para>
  817. /// If the given value is greater than the current length of the stream, the stream is expanded and the current
  818. /// position remains the same.
  819. /// </para>
  820. /// </remarks>
  821. public override void SetLength(long value)
  822. {
  823. #if NET8_0_OR_GREATER
  824. ArgumentOutOfRangeException.ThrowIfNegative(value);
  825. #else
  826. if (value < 0)
  827. {
  828. throw new ArgumentOutOfRangeException(nameof(value));
  829. }
  830. #endif
  831. // Lock down the file stream while we do this.
  832. lock (_lock)
  833. {
  834. CheckSessionIsOpen();
  835. if (!CanSeek)
  836. {
  837. throw new NotSupportedException("Seek is not supported.");
  838. }
  839. if (_bufferOwnedByWrite)
  840. {
  841. FlushWriteBuffer();
  842. }
  843. else
  844. {
  845. SetupWrite();
  846. }
  847. var attributes = _session.RequestFStat(_handle, nullOnError: false);
  848. attributes.Size = value;
  849. _session.RequestFSetStat(_handle, attributes);
  850. if (_position > value)
  851. {
  852. _position = value;
  853. }
  854. }
  855. }
  856. /// <summary>
  857. /// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.
  858. /// </summary>
  859. /// <param name="buffer">An array of bytes. This method copies <paramref name="count"/> bytes from <paramref name="buffer"/> to the current stream.</param>
  860. /// <param name="offset">The zero-based byte offset in <paramref name="buffer"/> at which to begin copying bytes to the current stream.</param>
  861. /// <param name="count">The number of bytes to be written to the current stream.</param>
  862. /// <exception cref="ArgumentException">The sum of <paramref name="offset"/> and <paramref name="count"/> is greater than the buffer length.</exception>
  863. /// <exception cref="ArgumentNullException"><paramref name="buffer"/> is <see langword="null"/>.</exception>
  864. /// <exception cref="ArgumentOutOfRangeException"><paramref name="offset"/> or <paramref name="count"/> is negative.</exception>
  865. /// <exception cref="IOException">An I/O error occurs.</exception>
  866. /// <exception cref="NotSupportedException">The stream does not support writing.</exception>
  867. /// <exception cref="ObjectDisposedException">Methods were called after the stream was closed.</exception>
  868. public override void Write(byte[] buffer, int offset, int count)
  869. {
  870. ThrowHelper.ThrowIfNull(buffer);
  871. #if NET8_0_OR_GREATER
  872. ArgumentOutOfRangeException.ThrowIfNegative(offset);
  873. ArgumentOutOfRangeException.ThrowIfNegative(count);
  874. #else
  875. if (offset < 0)
  876. {
  877. throw new ArgumentOutOfRangeException(nameof(offset));
  878. }
  879. if (count < 0)
  880. {
  881. throw new ArgumentOutOfRangeException(nameof(count));
  882. }
  883. #endif
  884. if ((buffer.Length - offset) < count)
  885. {
  886. throw new ArgumentException("Invalid array range.");
  887. }
  888. // Lock down the file stream while we do this.
  889. lock (_lock)
  890. {
  891. CheckSessionIsOpen();
  892. // Setup this object for writing.
  893. SetupWrite();
  894. // Write data to the file stream.
  895. while (count > 0)
  896. {
  897. // Determine how many bytes we can write to the buffer.
  898. var tempLen = _writeBufferSize - _bufferPosition;
  899. if (tempLen <= 0)
  900. {
  901. // flush write buffer, and mark it empty
  902. FlushWriteBuffer();
  903. // we can now write or buffer the full buffer size
  904. tempLen = _writeBufferSize;
  905. }
  906. // limit the number of bytes to write to the actual number of bytes requested
  907. if (tempLen > count)
  908. {
  909. tempLen = count;
  910. }
  911. // Can we short-cut the internal buffer?
  912. if (_bufferPosition == 0 && tempLen == _writeBufferSize)
  913. {
  914. using (var wait = new AutoResetEvent(initialState: false))
  915. {
  916. _session.RequestWrite(_handle, (ulong)_position, buffer, offset, tempLen, wait);
  917. }
  918. }
  919. else
  920. {
  921. // No: copy the data to the write buffer first.
  922. Buffer.BlockCopy(buffer, offset, GetOrCreateWriteBuffer(), _bufferPosition, tempLen);
  923. _bufferPosition += tempLen;
  924. }
  925. // Advance the buffer and stream positions.
  926. _position += tempLen;
  927. offset += tempLen;
  928. count -= tempLen;
  929. }
  930. // If the buffer is full, then do a speculative flush now,
  931. // rather than waiting for the next call to this method.
  932. if (_bufferPosition >= _writeBufferSize)
  933. {
  934. using (var wait = new AutoResetEvent(initialState: false))
  935. {
  936. _session.RequestWrite(_handle, (ulong)(_position - _bufferPosition), GetOrCreateWriteBuffer(), 0, _bufferPosition, wait);
  937. }
  938. _bufferPosition = 0;
  939. }
  940. }
  941. }
  942. /// <summary>
  943. /// Asynchronously writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.
  944. /// </summary>
  945. /// <param name="buffer">An array of bytes. This method copies <paramref name="count"/> bytes from <paramref name="buffer"/> to the current stream.</param>
  946. /// <param name="offset">The zero-based byte offset in <paramref name="buffer"/> at which to begin copying bytes to the current stream.</param>
  947. /// <param name="count">The number of bytes to be written to the current stream.</param>
  948. /// <param name="cancellationToken">The <see cref="CancellationToken"/> to observe.</param>
  949. /// <returns>A <see cref="Task"/> that represents the asynchronous write operation.</returns>
  950. /// <exception cref="ArgumentException">The sum of <paramref name="offset"/> and <paramref name="count"/> is greater than the buffer length.</exception>
  951. /// <exception cref="ArgumentNullException"><paramref name="buffer"/> is <see langword="null"/>.</exception>
  952. /// <exception cref="ArgumentOutOfRangeException"><paramref name="offset"/> or <paramref name="count"/> is negative.</exception>
  953. /// <exception cref="IOException">An I/O error occurs.</exception>
  954. /// <exception cref="NotSupportedException">The stream does not support writing.</exception>
  955. /// <exception cref="ObjectDisposedException">Methods were called after the stream was closed.</exception>
  956. public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
  957. {
  958. ThrowHelper.ThrowIfNull(buffer);
  959. #if NET8_0_OR_GREATER
  960. ArgumentOutOfRangeException.ThrowIfNegative(offset);
  961. ArgumentOutOfRangeException.ThrowIfNegative(count);
  962. #else
  963. if (offset < 0)
  964. {
  965. throw new ArgumentOutOfRangeException(nameof(offset));
  966. }
  967. if (count < 0)
  968. {
  969. throw new ArgumentOutOfRangeException(nameof(count));
  970. }
  971. #endif
  972. if ((buffer.Length - offset) < count)
  973. {
  974. throw new ArgumentException("Invalid array range.");
  975. }
  976. CheckSessionIsOpen();
  977. // Setup this object for writing.
  978. SetupWrite();
  979. // Write data to the file stream.
  980. while (count > 0)
  981. {
  982. // Determine how many bytes we can write to the buffer.
  983. var tempLen = _writeBufferSize - _bufferPosition;
  984. if (tempLen <= 0)
  985. {
  986. // flush write buffer, and mark it empty
  987. await FlushWriteBufferAsync(cancellationToken).ConfigureAwait(false);
  988. // we can now write or buffer the full buffer size
  989. tempLen = _writeBufferSize;
  990. }
  991. // limit the number of bytes to write to the actual number of bytes requested
  992. if (tempLen > count)
  993. {
  994. tempLen = count;
  995. }
  996. // Can we short-cut the internal buffer?
  997. if (_bufferPosition == 0 && tempLen == _writeBufferSize)
  998. {
  999. await _session.RequestWriteAsync(_handle, (ulong)_position, buffer, offset, tempLen, cancellationToken).ConfigureAwait(false);
  1000. }
  1001. else
  1002. {
  1003. // No: copy the data to the write buffer first.
  1004. Buffer.BlockCopy(buffer, offset, GetOrCreateWriteBuffer(), _bufferPosition, tempLen);
  1005. _bufferPosition += tempLen;
  1006. }
  1007. // Advance the buffer and stream positions.
  1008. _position += tempLen;
  1009. offset += tempLen;
  1010. count -= tempLen;
  1011. }
  1012. // If the buffer is full, then do a speculative flush now,
  1013. // rather than waiting for the next call to this method.
  1014. if (_bufferPosition >= _writeBufferSize)
  1015. {
  1016. await _session.RequestWriteAsync(_handle, (ulong)(_position - _bufferPosition), GetOrCreateWriteBuffer(), 0, _bufferPosition, cancellationToken).ConfigureAwait(false);
  1017. _bufferPosition = 0;
  1018. }
  1019. }
  1020. /// <summary>
  1021. /// Writes a byte to the current position in the stream and advances the position within the stream by one byte.
  1022. /// </summary>
  1023. /// <param name="value">The byte to write to the stream.</param>
  1024. /// <exception cref="IOException">An I/O error occurs. </exception>
  1025. /// <exception cref="NotSupportedException">The stream does not support writing, or the stream is already closed. </exception>
  1026. /// <exception cref="ObjectDisposedException">Methods were called after the stream was closed. </exception>
  1027. public override void WriteByte(byte value)
  1028. {
  1029. // Lock down the file stream while we do this.
  1030. lock (_lock)
  1031. {
  1032. CheckSessionIsOpen();
  1033. // Setup the object for writing.
  1034. SetupWrite();
  1035. var writeBuffer = GetOrCreateWriteBuffer();
  1036. // Flush the current buffer if it is full.
  1037. if (_bufferPosition >= _writeBufferSize)
  1038. {
  1039. using (var wait = new AutoResetEvent(initialState: false))
  1040. {
  1041. _session.RequestWrite(_handle, (ulong)(_position - _bufferPosition), writeBuffer, 0, _bufferPosition, wait);
  1042. }
  1043. _bufferPosition = 0;
  1044. }
  1045. // Write the byte into the buffer and advance the posn.
  1046. writeBuffer[_bufferPosition++] = value;
  1047. ++_position;
  1048. }
  1049. }
  1050. /// <summary>
  1051. /// Releases the unmanaged resources used by the <see cref="Stream"/> and optionally releases the managed resources.
  1052. /// </summary>
  1053. /// <param name="disposing"><see langword="true"/> to release both managed and unmanaged resources; <see langword="false"/> to release only unmanaged resources.</param>
  1054. protected override void Dispose(bool disposing)
  1055. {
  1056. base.Dispose(disposing);
  1057. if (_session != null)
  1058. {
  1059. if (disposing)
  1060. {
  1061. lock (_lock)
  1062. {
  1063. if (_session != null)
  1064. {
  1065. _canRead = false;
  1066. _canSeek = false;
  1067. _canWrite = false;
  1068. if (_handle != null)
  1069. {
  1070. if (_session.IsOpen)
  1071. {
  1072. if (_bufferOwnedByWrite)
  1073. {
  1074. FlushWriteBuffer();
  1075. }
  1076. _session.RequestClose(_handle);
  1077. }
  1078. _handle = null;
  1079. }
  1080. _session = null;
  1081. }
  1082. }
  1083. }
  1084. }
  1085. }
  1086. private byte[] GetOrCreateReadBuffer()
  1087. {
  1088. _readBuffer ??= new byte[_readBufferSize];
  1089. return _readBuffer;
  1090. }
  1091. private byte[] GetOrCreateWriteBuffer()
  1092. {
  1093. _writeBuffer ??= new byte[_writeBufferSize];
  1094. return _writeBuffer;
  1095. }
  1096. /// <summary>
  1097. /// Flushes the read data from the buffer.
  1098. /// </summary>
  1099. private void FlushReadBuffer()
  1100. {
  1101. _bufferPosition = 0;
  1102. _bufferLen = 0;
  1103. }
  1104. /// <summary>
  1105. /// Flush any buffered write data to the file.
  1106. /// </summary>
  1107. private void FlushWriteBuffer()
  1108. {
  1109. if (_bufferPosition > 0)
  1110. {
  1111. using (var wait = new AutoResetEvent(initialState: false))
  1112. {
  1113. _session.RequestWrite(_handle, (ulong)(_position - _bufferPosition), _writeBuffer, 0, _bufferPosition, wait);
  1114. }
  1115. _bufferPosition = 0;
  1116. }
  1117. }
  1118. private async Task FlushWriteBufferAsync(CancellationToken cancellationToken)
  1119. {
  1120. if (_bufferPosition > 0)
  1121. {
  1122. await _session.RequestWriteAsync(_handle, (ulong)(_position - _bufferPosition), _writeBuffer, 0, _bufferPosition, cancellationToken).ConfigureAwait(false);
  1123. _bufferPosition = 0;
  1124. }
  1125. }
  1126. /// <summary>
  1127. /// Setups the read.
  1128. /// </summary>
  1129. private void SetupRead()
  1130. {
  1131. if (!CanRead)
  1132. {
  1133. throw new NotSupportedException("Read not supported.");
  1134. }
  1135. if (_bufferOwnedByWrite)
  1136. {
  1137. FlushWriteBuffer();
  1138. _bufferOwnedByWrite = false;
  1139. }
  1140. }
  1141. /// <summary>
  1142. /// Setups the write.
  1143. /// </summary>
  1144. private void SetupWrite()
  1145. {
  1146. if (!CanWrite)
  1147. {
  1148. throw new NotSupportedException("Write not supported.");
  1149. }
  1150. if (!_bufferOwnedByWrite)
  1151. {
  1152. FlushReadBuffer();
  1153. _bufferOwnedByWrite = true;
  1154. }
  1155. }
  1156. private void CheckSessionIsOpen()
  1157. {
  1158. ThrowHelper.ThrowObjectDisposedIf(_session is null, this);
  1159. if (!_session.IsOpen)
  1160. {
  1161. throw new ObjectDisposedException(GetType().FullName, "Cannot access a closed SFTP session.");
  1162. }
  1163. }
  1164. }
  1165. }