PipeStream.Read Método

Definição

Sobrecargas

Read(Span<Byte>)

Lê uma sequência de bytes do fluxo em buffer atual, grava-os em uma matriz de bytes e avança a posição no fluxo até o número de bytes lidos.

Read(Byte[], Int32, Int32)

Lê um bloco de bytes de um fluxo e grava os dados em um buffer especificado, começando em uma posição especificada para um tamanho especificado.

Read(Span<Byte>)

Lê uma sequência de bytes do fluxo em buffer atual, grava-os em uma matriz de bytes e avança a posição no fluxo até o número de bytes lidos.

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>

Uma região da memória. Quando este método retorna, o conteúdo desta região é substituído pelos bytes lidos da fonte atual.

Retornos

Int32

O número total de bytes de leitura para o buffer. Isso pode ser menor que o número de bytes alocados em buffer se esses muitos bytes não estão disponíveis no momento ou pode ser zero (0) caso o final do fluxo seja atingido.

Exceções

O número de bytes lidos foi maior que o tamanho do buffer.

Não há suporte para leitura no fluxo.

Não é possível acessar um pipe fechado.

O pipe ainda não foi conectado.

- ou -

O pipe está em um estado desconectado.

- ou -

O identificador de pipe não foi definido. (A implementação de PipeStream chamou InitializeHandle(SafePipeHandle, Boolean, Boolean)?)

Comentários

Use a CanRead propriedade para determinar se o objeto atual PipeStream dá suporte a operações de leitura.

Use o ReadAsync método para ler de forma assíncrona do fluxo atual.

Esse método lê um máximo de buffer.Length bytes do fluxo atual e os armazena em buffer. A posição atual dentro do fluxo é avançada pelo número de bytes lidos; no entanto, se ocorrer uma exceção, a posição atual dentro do fluxo permanecerá inalterada.

Esse método será bloqueado até que pelo menos um byte de dados possa ser lido, caso nenhum dado esteja disponível.

Esse método retorna 0 somente quando não há mais dados no fluxo e não é esperado mais (como um soquete fechado ou fim do arquivo).

Esse método é livre para retornar menos bytes do que o solicitado, mesmo que o final do fluxo não tenha sido atingido.

Use BinaryReader para ler tipos de dados primitivos.

Aplica-se a

Read(Byte[], Int32, Int32)

Lê um bloco de bytes de um fluxo e grava os dados em um buffer especificado, começando em uma posição especificada para um tamanho especificado.

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[]

Quando este método retorna, ele contém a matriz de bytes especificada com os valores entre offset e (offset + count -1) substituídos pelos bytes lidos da fonte atual.

offset
Int32

O deslocamento de bytes na matriz de buffer no qual os bytes que são lidos serão colocados.

count
Int32

O número máximo de bytes a serem lidos.

Retornos

Int32

O número total de bytes lidos no buffer. Poderá ser menor que o número de bytes solicitado se esse número de bytes não estiver disponível no momento ou 0 se o fim do fluxo for atingido.

Atributos

Exceções

buffer é null.

offset é menor que 0.

- ou - count é menor que 0.

count é maior que o número de bytes disponível no buffer.

O pipe está fechado.

O pipe não dá suporte a operações de leitura.

O pipe está desconectado, esperando para conectar-se ou o identificador não foi definido.

Ocorreu um erro de E/S.

Exemplos

O exemplo a seguir cria um cliente de pipe anônimo e um servidor de pipe. O servidor de pipe usa o Read método para ler uma série de bytes do cliente de pipe como um código de validação. O cliente de pipe e o servidor de pipe fazem parte do mesmo exemplo. A parte do servidor do exemplo cria um processo de cliente e passa um identificador de pipe anônimo como um argumento.

#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

Comentários

Use a CanRead propriedade para determinar se o objeto atual PipeStream dá suporte a operações de leitura.

Chamar os blocos de Read método até count que os bytes sejam lidos ou o final do fluxo seja atingido. Para operações de leitura assíncronas, consulte BeginRead e EndRead.

Aplica-se a