PipeStream.Read Método

Definición

Sobrecargas

Read(Span<Byte>)

Lee una secuencia de bytes de la secuencia actual, las escribe en una matriz de bytes y avanza la posición dentro de la secuencia el número de bytes leídos.

Read(Byte[], Int32, Int32)

Lee un bloque de bytes de una secuencia y escribe los datos en un búfer especificado, a partir de una posición especificada y con una longitud especificada.

Read(Span<Byte>)

Source:
PipeStream.Unix.cs
Source:
PipeStream.Unix.cs
Source:
PipeStream.Unix.cs

Lee una secuencia de bytes de la secuencia actual, las escribe en una matriz de bytes y avanza la posición dentro de la secuencia el número de bytes leídos.

public:
 override int Read(Span<System::Byte> buffer);
public override int Read (Span<byte> buffer);
override this.Read : Span<byte> -> int
Public Overrides Function Read (buffer As Span(Of Byte)) As Integer

Parámetros

buffer
Span<Byte>

Región de memoria. Cuando este método finaliza, el contenido de esta región se reemplaza por los bytes leídos del origen actual.

Devoluciones

Número total de bytes leídos en buffer. Puede ser menor que el número de bytes asignado en buffer si esos bytes no están disponibles en ese momento, o cero (0) si se ha alcanzado el final de la secuencia.

Excepciones

Número de bytes leídos era mayor que la longitud del búfer.

La secuencia no admite lectura.

No se puede tener acceso a una canalización cerrada.

La canalización aún no se ha conectado.

o bien

La canalización está en estado desconectado.

o bien

La canalización no se estableció. ¿Llamó la implementación de PipeStream a InitializeHandle(SafePipeHandle, Boolean, Boolean)?

Comentarios

Utilice la CanRead propiedad para determinar si el objeto actual PipeStream admite operaciones de lectura.

Use el ReadAsync método para leer de forma asincrónica desde la secuencia actual.

Este método lee un máximo de buffer.Length bytes de la secuencia actual y los almacena en buffer. La posición actual dentro de la secuencia está avanzada por el número de bytes leídos; sin embargo, si se produce una excepción, la posición actual dentro de la secuencia permanece sin cambios.

Este método se bloqueará hasta que se pueda leer al menos un byte de datos, en caso de que no haya datos disponibles.

Este método devuelve 0 solo cuando no hay más datos en la secuencia y no se espera más (por ejemplo, un socket cerrado o el final del archivo).

Este método es gratuito para devolver menos bytes de los solicitados, incluso si no se ha alcanzado el final de la secuencia.

Se usa BinaryReader para leer tipos de datos primitivos.

Se aplica a

Read(Byte[], Int32, Int32)

Source:
PipeStream.Unix.cs
Source:
PipeStream.Unix.cs
Source:
PipeStream.Unix.cs

Lee un bloque de bytes de una secuencia y escribe los datos en un búfer especificado, a partir de una posición especificada y con una longitud especificada.

public:
 override int Read(cli::array <System::Byte> ^ buffer, int offset, int count);
public override int Read (byte[] buffer, int offset, int count);
[System.Security.SecurityCritical]
public override int Read (byte[] buffer, int offset, int count);
override this.Read : byte[] * int * int -> int
[<System.Security.SecurityCritical>]
override this.Read : byte[] * int * int -> int
Public Overrides Function Read (buffer As Byte(), offset As Integer, count As Integer) As Integer

Parámetros

buffer
Byte[]

Cuando este método devuelve un valor, contiene la matriz de bytes especificada con los valores entre offset y (offset + count - 1) reemplazados por los bytes leídos desde el origen actual.

offset
Int32

Desplazamiento en bytes de la matriz de buffer en la que se colocarán los bytes que se leen.

count
Int32

Número máximo de bytes que se pueden leer.

Devoluciones

El número total de bytes leídos en buffer. Puede ser menor que el número de bytes solicitado si ese número de bytes no está disponible actualmente o puede ser 0 si se alcanzó el final de la secuencia.

Atributos

Excepciones

buffer es null.

offset es menor que 0.

O bien

count es menor que 0.

count es mayor que el número de bytes disponible en buffer.

La canalización está cerrada.

La canalización no admite operaciones de lectura.

La canalización está desconectada, a la espera de conectarse, o bien, no se ha establecido el identificador.

Error de E/S.

Ejemplos

En el ejemplo siguiente se crea un cliente de canalización anónimo y un servidor de canalización. El servidor de canalización usa el Read método para leer una serie de bytes del cliente de canalización como código de validación. Tanto el cliente de canalización como el servidor de canalización forman parte del mismo ejemplo. La parte del servidor del ejemplo crea un proceso de cliente y lo pasa como argumento un identificador de canalización anónimo.

#using <System.dll>
#using <System.Core.dll>

using namespace System;
using namespace System::IO;
using namespace System::IO::Pipes;
using namespace System::Diagnostics;

ref class PipeStreamExample
{
private:
    static array<Byte>^ matchSign = {9, 0, 9, 0};

public:
    static void Main()
    {
        array<String^>^ args = Environment::GetCommandLineArgs();
        if (args->Length < 2)
        {
            Process^ clientProcess = gcnew Process();

            clientProcess->StartInfo->FileName = Environment::CommandLine;

            AnonymousPipeServerStream^ pipeServer =
                gcnew AnonymousPipeServerStream(PipeDirection::In,
                HandleInheritability::Inheritable);
            // Pass the client process a handle to the server.
            clientProcess->StartInfo->Arguments = pipeServer->GetClientHandleAsString();
            clientProcess->StartInfo->UseShellExecute = false;
            Console::WriteLine("[SERVER] Starting client process...");
            clientProcess->Start();

            pipeServer->DisposeLocalCopyOfClientHandle();

            try
            {
                if (WaitForClientSign(pipeServer))
                {
                    Console::WriteLine("[SERVER] Valid sign code received!");
                }
                else
                {
                    Console::WriteLine("[SERVER] Invalid sign code received!");
                }
            }
            catch (IOException^ e)
            {
                 Console::WriteLine("[SERVER] Error: {0}", e->Message);
            }
            clientProcess->WaitForExit();
            clientProcess->Close();
            Console::WriteLine("[SERVER] Client quit. Server terminating.");
        }
        else
        {
            PipeStream^ pipeClient =
                gcnew AnonymousPipeClientStream(PipeDirection::Out, args[1]);
            try
            {
                Console::WriteLine("[CLIENT] Sending sign code...");
                SendClientSign(pipeClient);
            }
            catch (IOException^ e)
            {
                Console::WriteLine("[CLIENT] Error: {0}", e->Message);
            }
            Console::WriteLine("[CLIENT] Terminating.");
        }
    }

private:
    static bool WaitForClientSign(PipeStream^ inStream)
    {
        array<Byte>^ inSign = gcnew array<Byte>(matchSign->Length);
        int len = inStream->Read(inSign, 0, matchSign->Length);
        bool valid = len == matchSign->Length;

        while (valid && len-- > 0)
        {
            valid = valid && (matchSign[len] == inSign[len]);
        }
        return valid;
    }

    static void SendClientSign(PipeStream^ outStream)
    {
        outStream->Write(matchSign, 0, matchSign->Length);
    }
};

int main()
{
    PipeStreamExample::Main();
}
using System;
using System.IO;
using System.IO.Pipes;
using System.Diagnostics;

class PipeStreamExample
{
    private static byte[] matchSign = {9, 0, 9, 0};

    public static void Main()
    {
        string[] args = Environment.GetCommandLineArgs();
        if (args.Length < 2)
        {
            Process clientProcess = new Process();

            clientProcess.StartInfo.FileName = Environment.CommandLine;

            using (AnonymousPipeServerStream pipeServer =
                new AnonymousPipeServerStream(PipeDirection.In,
                HandleInheritability.Inheritable))
            {
                // Pass the client process a handle to the server.
                clientProcess.StartInfo.Arguments = pipeServer.GetClientHandleAsString();
                clientProcess.StartInfo.UseShellExecute = false;
                Console.WriteLine("[SERVER] Starting client process...");
                clientProcess.Start();

                pipeServer.DisposeLocalCopyOfClientHandle();

                try
                {
                    if (WaitForClientSign(pipeServer))
                    {
                        Console.WriteLine("[SERVER] Valid sign code received!");
                    }
                    else
                    {
                        Console.WriteLine("[SERVER] Invalid sign code received!");
                    }
                }
                catch (IOException e)
                {
                    Console.WriteLine("[SERVER] Error: {0}", e.Message);
                }
            }
            clientProcess.WaitForExit();
            clientProcess.Close();
            Console.WriteLine("[SERVER] Client quit. Server terminating.");
        }
        else
        {
            using (PipeStream pipeClient = new AnonymousPipeClientStream(PipeDirection.Out, args[1]))
            {
                try
                {
                    Console.WriteLine("[CLIENT] Sending sign code...");
                    SendClientSign(pipeClient);
                }
                catch (IOException e)
                {
                     Console.WriteLine("[CLIENT] Error: {0}", e.Message);
                }
            }
            Console.WriteLine("[CLIENT] Terminating.");
        }
    }

    private static bool WaitForClientSign(PipeStream inStream)
    {
        byte[] inSign = new byte[matchSign.Length];
        int len = inStream.Read(inSign, 0, matchSign.Length);
        bool valid = len == matchSign.Length;

        while (valid && len-- > 0)
        {
            valid = valid && (matchSign[len] == inSign[len]);
        }
        return valid;
    }

    private static void SendClientSign(PipeStream outStream)
    {
        outStream.Write(matchSign, 0, matchSign.Length);
    }
}
Imports System.IO
Imports System.IO.Pipes
Imports System.Diagnostics

Class PipeStreamExample
    Private Shared matchSign() As Byte = {9, 0, 9, 0}

    Public Shared Sub Main()
        Dim args() As String = Environment.GetCommandLineArgs()
        If args.Length < 2 Then
            Dim clientProcess As New Process()

            clientProcess.StartInfo.FileName = Environment.CommandLine

            Using pipeServer As New AnonymousPipeServerStream( _
                PipeDirection.In, HandleInheritability.Inheritable)

                ' Pass the client process a handle to the server.
                clientProcess.StartInfo.Arguments = pipeServer.GetClientHandleAsString()
                clientProcess.StartInfo.UseShellExecute = false
                Console.WriteLine("[SERVER] Starting client process...")
                clientProcess.Start()

                pipeServer.DisposeLocalCopyOfClientHandle()

                Try
                    If WaitForClientSign(pipeServer) Then
                        Console.WriteLine("[SERVER] Valid sign code received!")
                    Else
                        Console.WriteLine("[SERVER] Invalid sign code received!")
                    End If
                Catch e As IOException
                    Console.WriteLine("[SERVER] Error: {0}", e.Message)
                End Try
            End Using
            clientProcess.WaitForExit()
            clientProcess.Close()
            Console.WriteLine("[SERVER] Client quit. Server terminating.")
        Else
            Using pipeClient As PipeStream = New AnonymousPipeClientStream(PipeDirection.Out, args(1))
                Try
                    Console.WriteLine("[CLIENT] Sending sign code...")
                    SendClientSign(pipeClient)
                Catch e As IOException
                    Console.WriteLine("[CLIENT] Error: {0}", e.Message)
                End Try
            End Using
            Console.WriteLine("[CLIENT] Terminating.")
        End If
    End Sub

    Private Shared Function WaitForClientSign(inStream As PipeStream) As Boolean
        Dim inSign() As Byte = Array.CreateInstance(GetType(Byte), matchSign.Length)
        Dim len As Integer = inStream.Read(inSign, 0, matchSign.Length)
        Dim valid = len.Equals(matchSign.Length)

        While len > 0
            len -= 1
            valid = valid And (matchSign(len).Equals(inSign(len)))
        End While
        Return valid
    End Function

    Private Shared Sub SendClientSign(outStream As PipeStream)
        outStream.Write(matchSign, 0, matchSign.Length)
    End Sub
End Class

Comentarios

Utilice la CanRead propiedad para determinar si el objeto actual PipeStream admite operaciones de lectura.

La llamada al Read método se bloquea hasta count que se leen bytes o se alcanza el final de la secuencia. Para las operaciones de lectura asincrónicas, vea BeginRead y EndRead.

Se aplica a