PipeStream.Read 方法

定义

重载

Read(Span<Byte>)

从当前流中读取一个字节序列,将其写入字节数组,并按读取的字节数向前移动流中的位置。Reads a sequence of bytes from the current stream, writes them to a byte array, and advances the position within the stream by the number of bytes read.

Read(Byte[], Int32, Int32)

从指定长度的指定位置开始,从流中读取一个字节块,并将数据写入指定的缓冲区。Reads a block of bytes from a stream and writes the data to a specified buffer starting at a specified position for a specified length.

Read(Span<Byte>)

从当前流中读取一个字节序列,将其写入字节数组,并按读取的字节数向前移动流中的位置。Reads a sequence of bytes from the current stream, writes them to a byte array, and advances the position within the stream by the number of bytes read.

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>

内存的区域。A region of memory. 当此方法返回时,此区域的内容将替换为从当前源读取的字节。When this method returns, the contents of this region are replaced by the bytes read from the current source.

返回

读入 buffer 中的总字节数。The total number of bytes read into the buffer. 如果很多字节当前不可用,则这可小于在 buffer 中分配的字节数;如果已到达流结尾,则为零 (0)。This can be less than the number of bytes allocated in buffer if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.

异常

读取的字节数长于缓冲区长度。The number of bytes read was longer than the buffer length.

流不支持读取。The stream does not support reading.

无法访问关闭的管道。Cannot access a closed pipe.

管道尚未连接。The pipe hasn't been connected yet.

- 或 --or-

管道处于断开连接状态。The pipe is in a disconnected state.

- 或 --or-

尚未设置管道句柄。The pipe handle has not been set. (你的 PipeStream 实现是否调用 InitializeHandle(SafePipeHandle, Boolean, Boolean)(Did your PipeStream implementation call InitializeHandle(SafePipeHandle, Boolean, Boolean)?

注解

使用 CanRead 属性来确定当前 PipeStream 对象是否支持读操作。Use the CanRead property to determine whether the current PipeStream object supports read operations.

使用 ReadAsync 方法从当前流中异步读取。Use the ReadAsync method to read asynchronously from the current stream.

此方法从当前流中读取最多 buffer.Length 个字节,并将它们存储在 buffer中。This method reads a maximum of buffer.Length bytes from the current stream and stores them in buffer. 流中的当前位置按读取的字节数提前;但是,如果发生异常,则流中的当前位置将保持不变。The current position within the stream is advanced by the number of bytes read; however, if an exception occurs, the current position within the stream remains unchanged.

如果没有数据可用,则此方法将被阻止,直到至少有一个字节的数据可供读取。This method will block until at least one byte of data can be read, in the event that no data is available.

仅当流中没有更多的数据,但不需要更多的数据(如闭合的套接字或文件尾)时,此方法才返回0。This method returns 0 only when there is no more data in the stream and no more is expected (such as a closed socket or end of file).

即使尚未到达流的末尾,此方法也可以自由返回比所请求的更少的字节。This method is free to return fewer bytes than requested even if the end of the stream has not been reached.

使用 BinaryReader 读取基元数据类型。Use BinaryReader for reading primitive data types.

Read(Byte[], Int32, Int32)

从指定长度的指定位置开始,从流中读取一个字节块,并将数据写入指定的缓冲区。Reads a block of bytes from a stream and writes the data to a specified buffer starting at a specified position for a specified length.

public:
 override int Read(cli::array <System::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
Public Overrides Function Read (buffer As Byte(), offset As Integer, count As Integer) As Integer

参数

buffer
Byte[]

当此方法返回时,包含指定的字节数组,此数组中 offset 和 (offset + count - 1) 之间的值被从当前源中读取的字节所替换。When this method returns, contains the specified byte array with the values between offset and (offset + count - 1) replaced by the bytes read from the current source.

offset
Int32

buffer 数组中的字节偏移量,其中读取的字节将被替换。The byte offset in the buffer array at which the bytes that are read will be placed.

count
Int32

要读取的最大字节数。The maximum number of bytes to read.

返回

读取到 buffer 的总字节数。The total number of bytes that are read into buffer. 如果当前可用的字节数没有请求的那么多,则此数小于请求的字节数;或如果已到达流的末尾,则为零。This might be less than the number of bytes requested if that number of bytes is not currently available, or 0 if the end of the stream is reached.

属性

异常

buffernullbuffer is null.

offset 小于 0。offset is less than 0.

- 或 --or- count 小于 0。count is less than 0.

count 大于 buffer 中可用的字节数。count is greater than the number of bytes available in buffer.

管道已关闭。The pipe is closed.

管道不支持读取操作。The pipe does not support read operations.

管道已断开连接,正在等待连接,或尚未设置句柄。The pipe is disconnected, waiting to connect, or the handle has not been set.

发生了 I/O 错误。Any I/O error occurred.

示例

下面的示例创建一个匿名管道客户端和管道服务器。The following example creates an anonymous pipe client and pipe server. 管道服务器使用 Read 方法将管道客户端中的一系列字节作为验证代码进行读取。The pipe server uses the Read method to read a series of bytes from the pipe client as a validation code. 管道客户端和管道服务器都属于同一示例。Both the pipe client and the pipe server are part of the same example. 该示例的服务器部分创建一个客户端进程,并将匿名管道句柄作为参数传递。The server portion of the example creates a client process and passes it an anonymous pipe handle as an 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

注解

使用 CanRead 属性来确定当前 PipeStream 对象是否支持读操作。Use the CanRead property to determine whether the current PipeStream object supports read operations.

调用 Read 方法将会阻止,直到读取 count 字节或到达流的末尾。Calling the Read method blocks until count bytes are read or the end of the stream is reached. 有关异步读取操作,请参阅 BeginReadEndReadFor asynchronous read operations, see BeginRead and EndRead.

适用于