PipeStream.Read 方法

定義

多載

Read(Span<Byte>)

從目前的資料流讀取位元組序列、將其寫入至位元組陣列,並依讀取的位元組數將資料流中位置往前移。

Read(Byte[], Int32, Int32)

從資料流讀取位元組區塊,並將資料寫入至起始於指定位置且具有指定長度的指定緩衝區。

Read(Span<Byte>)

來源:
PipeStream.Unix.cs
來源:
PipeStream.Unix.cs
來源:
PipeStream.Unix.cs

從目前的資料流讀取位元組序列、將其寫入至位元組陣列,並依讀取的位元組數將資料流中位置往前移。

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

參數

buffer
Span<Byte>

記憶體區域。 當這個方法傳回時,讀取自目前來源的位元組會取代此區域內容。

傳回

讀取到 buffer 中的位元組總數。 如果目前無法取得足夠的位元組,則這個數目可能小於 buffer 所配置的位元組數;如果已經到達資料流結尾,則為零 (0)。

例外狀況

讀取的位元組數大於緩衝區長度。

資料流不支援讀取。

無法存取關閉的管道。

管道尚未連接。

-或-

管道處於中斷連接狀態。

-或-

尚未設定管道控制代碼。 (您的 PipeStream 實作是否呼叫 InitializeHandle(SafePipeHandle, Boolean, Boolean)

備註

CanRead使用 屬性來判斷目前 PipeStream 物件是否支援讀取作業。

ReadAsync使用 方法,以非同步方式從目前的資料流程讀取。

這個方法會從目前的資料流程讀取最大位元組, buffer.Length 並將其儲存在 buffer 中。 資料流程中的目前位置會依讀取的位元組數目進階;不過,如果發生例外狀況,資料流程中的目前位置會保持不變。

如果沒有任何資料可用,這個方法將會封鎖,直到可以讀取至少一個位元組的資料為止。

只有在資料流程中沒有其他資料,而且預期不會再傳回 0 (,例如關閉的通訊端或檔案結尾) 。

即使尚未到達資料流程結尾,這個方法仍可傳回比要求的位元組少。

用於 BinaryReader 讀取基本資料類型。

適用於

Read(Byte[], Int32, Int32)

來源:
PipeStream.Unix.cs
來源:
PipeStream.Unix.cs
來源:
PipeStream.Unix.cs

從資料流讀取位元組區塊,並將資料寫入至起始於指定位置且具有指定長度的指定緩衝區。

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

參數

buffer
Byte[]

當這個方法傳回時,會包含指定的位元組陣列,這個陣列具有介於 offset 到 (offset + count - 1) 之間的值,已由讀取自目前來源的位元組所取代。

offset
Int32

要將讀取位元組放入其中之 buffer 陣列中的位元組位移 (Offset)。

count
Int32

要讀取的最大位元組數。

傳回

讀入 buffer 中的位元組總數。 如果目前無法取得要求的位元組數目,此數目可能小於該位元組數目;如果已到達資料流結尾,則此數目為 0。

屬性

例外狀況

buffernull

offset 小於 0。

-或-

count 小於 0。

count 大於 buffer 中的可用位元組數目。

管道已關閉。

管道不支援讀取作業。

管道已中斷連接、正在等候連接,或尚未設定控制代碼。

發生任何 I/O 錯誤。

範例

下列範例會建立匿名管道用戶端和管道伺服器。 管道伺服器會 Read 使用 方法,從管道用戶端讀取一系列位元組做為驗證碼。 管道用戶端和管道伺服器都是相同範例的一部分。 此範例的伺服器部分會建立用戶端進程,並將匿名管道控制碼傳遞為引數。

#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

備註

CanRead使用 屬性來判斷目前 PipeStream 物件是否支援讀取作業。

呼叫 方法會 Read 封鎖 ,直到 count 讀取位元組或到達資料流程結尾為止。 如需非同步讀取作業,請參閱 BeginReadEndRead

適用於