Flush Method

System.Net.Security.SslStream
public override void Flush();

Description

Flushes the stream, causing any buffered data to be written to the underlying stream.

This method is overridden from the base class System.IO.Stream. It is used to ensure that any data that has been written to the SslStream but not yet sent over the network is transmitted.

Return Value

None.

Exceptions

ObjectDisposedException The stream has been closed.
IOException An I/O error occurred while flushing the stream.

Remarks

Calling Flush ensures that all buffered data is sent to the underlying stream. For an SslStream, this means that the encrypted data is written to the transport stream. You typically call this method when you want to make sure that all pending data is sent before performing another operation, such as closing the stream or performing a new read operation.

Note that flushing the stream does not necessarily mean that the data has been received by the remote party. It only guarantees that the data has been passed to the underlying transport mechanism.

Example

using System; using System.Net.Security; using System.Net.Sockets; using System.Security.Cryptography.X509Certificates; using System.Text; public class SslStreamExample { public static void ExampleFlush(TcpClient client, X509Certificate serverCertificate) { using (SslStream sslStream = new SslStream( client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null)) { try { // Authenticate the server (client side) sslStream.AuthenticateAsClient("your.server.name"); Console.WriteLine("Client authenticated."); // Write some data byte[] message = Encoding.UTF8.GetBytes("Hello from client!"); sslStream.Write(message); // Flush the stream to ensure data is sent immediately sslStream.Flush(); Console.WriteLine("Stream flushed."); // Continue with other operations... } catch (Exception ex) { Console.WriteLine($"An error occurred: {ex.Message}"); } } } public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { if (sslPolicyErrors == SslPolicyErrors.None) return true; Console.WriteLine("Certificate error: " + sslPolicyErrors); // Do not allow this exception to keep the connection open. return false; } }