PipeStream.Read 方法

定义

重载

Read(Span<Byte>)

从当前流中读取一个字节序列,将其写入字节数组,并按读取的字节数向前移动流中的位置。

Read(Byte[], Int32, Int32)

从指定长度的指定位置开始,从流中读取一个字节块,并将数据写入指定的缓冲区。

Read(Span<Byte>)

Source:
PipeStream.Unix.cs
Source:
PipeStream.Unix.cs
Source:
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)

Source:
PipeStream.Unix.cs
Source:
PipeStream.Unix.cs
Source:
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 数组中的字节偏移量,其中读取的字节将被替换。

count
Int32

最多读取的字节数。

返回

读取到 buffer 的总字节数。 如果当前可用的字节数没有请求的那么多,则此数小于请求的字节数;或如果已到达流的末尾,则为零。

属性

例外

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

适用于