Udostępnij przez


PipeStream.Read Metoda

Definicja

Przeciążenia

Read(Span<Byte>)

Odczytuje sekwencję bajtów z bieżącego strumienia, zapisuje je w tablicy bajtów i rozwija pozycję w strumieniu według liczby odczytanych bajtów.

Read(Byte[], Int32, Int32)

Odczytuje blok bajtów ze strumienia i zapisuje dane w określonym buforze, zaczynając od określonej pozycji dla określonej długości.

Read(Span<Byte>)

Źródło:
PipeStream.Unix.cs
Źródło:
PipeStream.Unix.cs
Źródło:
PipeStream.Unix.cs

Odczytuje sekwencję bajtów z bieżącego strumienia, zapisuje je w tablicy bajtów i rozwija pozycję w strumieniu według liczby odczytanych bajtów.

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

Parametry

buffer
Span<Byte>

Region pamięci. Gdy ta metoda zwróci wartość , zawartość tego regionu jest zastępowana przez bajty odczytane z bieżącego źródła.

Zwraca

Całkowita liczba bajtów odczytanych w obiekcie buffer. Może to być mniejsze niż liczba bajtów przydzielonych, buffer jeśli liczba bajtów nie jest obecnie dostępna lub zero (0), jeśli koniec strumienia został osiągnięty.

Wyjątki

Liczba odczytanych bajtów była dłuższa niż długość buforu.

Strumień nie obsługuje odczytu.

Nie można uzyskać dostępu do zamkniętego potoku.

Rura nie została jeszcze połączona.

-lub-

Potok jest w stanie rozłączenia.

-lub-

Uchwyt potoku nie został ustawiony. (Czy implementacja została wywołana PipeStreamInitializeHandle(SafePipeHandle, Boolean, Boolean)?

Uwagi

Użyj właściwości , CanRead aby określić, czy bieżący PipeStream obiekt obsługuje operacje odczytu.

ReadAsync Użyj metody , aby odczytywać asynchronicznie z bieżącego strumienia.

Ta metoda odczytuje maksymalnie buffer.Length bajty z bieżącego strumienia i przechowuje je w pliku buffer. Bieżące położenie w strumieniu jest zaawansowane przez liczbę odczytanych bajtów; jednak w przypadku wystąpienia wyjątku bieżące położenie w strumieniu pozostaje niezmienione.

Ta metoda zostanie zablokowana do momentu odczytania co najmniej jednego bajtu danych w przypadku, gdy żadne dane nie są dostępne.

Ta metoda zwraca wartość 0 tylko wtedy, gdy nie ma więcej danych w strumieniu i nie jest już oczekiwana (np. zamknięte gniazdo lub koniec pliku).

Ta metoda umożliwia zwrócenie mniejszej liczby bajtów niż zażądano, nawet jeśli koniec strumienia nie został osiągnięty.

Służy BinaryReader do odczytywania typów danych pierwotnych.

Dotyczy

Read(Byte[], Int32, Int32)

Źródło:
PipeStream.Unix.cs
Źródło:
PipeStream.Unix.cs
Źródło:
PipeStream.Unix.cs

Odczytuje blok bajtów ze strumienia i zapisuje dane w określonym buforze, zaczynając od określonej pozycji dla określonej długości.

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

Parametry

buffer
Byte[]

Gdy ta metoda zwraca wartość , zawiera określoną tablicę bajtów z wartościami między offset i (offset + count - 1) zastąpionymi bajtami odczytanymi z bieżącego źródła.

offset
Int32

Przesunięcie bajtu w tablicy buffer , w której zostaną umieszczone odczytane bajty.

count
Int32

Maksymalna liczba bajtów do odczytania.

Zwraca

Całkowita liczba bajtów odczytanych w pliku buffer. Może to być mniejsza niż liczba bajtów żądanych, jeśli ta liczba bajtów nie jest obecnie dostępna, lub 0, jeśli koniec strumienia zostanie osiągnięty.

Atrybuty

Wyjątki

buffer to null.

offset wartość jest mniejsza niż 0.

-lub-

count wartość jest mniejsza niż 0.

count jest większa niż liczba bajtów dostępnych w pliku buffer.

Rura jest zamknięta.

Potok nie obsługuje operacji odczytu.

Potok jest odłączony, czeka na połączenie lub nie ustawiono uchwytu.

Wystąpił dowolny błąd we/wy.

Przykłady

W poniższym przykładzie tworzony jest anonimowy klient potoku i serwer potoku. Serwer potoku Read używa metody do odczytywania serii bajtów od klienta potoku jako kodu weryfikacji. Zarówno klient potoku, jak i serwer potoku są częścią tego samego przykładu. Część serwera w przykładzie tworzy proces klienta i przekazuje mu anonimowy uchwyt potoku jako argument.

#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

Uwagi

Użyj właściwości , CanRead aby określić, czy bieżący PipeStream obiekt obsługuje operacje odczytu.

Read Wywoływanie bloków metody do momentu count odczytania bajtów lub osiągnięcia końca strumienia. W przypadku operacji odczytu asynchronicznego zobacz BeginRead i EndRead.

Dotyczy