BinaryReader.ReadBytes(Int32) 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
將目前資料流中的指定位元組數讀入位元組陣列中,並將目前的位置前移該位元組數。
public:
virtual cli::array <System::Byte> ^ ReadBytes(int count);
public virtual byte[] ReadBytes (int count);
abstract member ReadBytes : int -> byte[]
override this.ReadBytes : int -> byte[]
Public Overridable Function ReadBytes (count As Integer) As Byte()
參數
- count
- Int32
要讀取的位元組數。 這個值必須是 0 或非負數,否則會發生例外狀況。
傳回
Byte[]
位元組陣列,含有自基礎資料流讀取的資料。 如果已到達資料流末端,這可能會小於要求的位元組數。
例外狀況
欲讀取的解碼字元數大於 count
。 如果 Unicode 解碼器傳回後援字元或 Surrogate 組,就會發生這個情況。
發生 I/O 錯誤。
資料流已關閉。
count
為負。
範例
下列程式代碼範例示範如何使用記憶體作為備份儲存區來寫入二進位數據,然後確認數據已正確寫入。
using namespace System;
using namespace System::IO;
int main()
{
const int arrayLength = 1000;
// Create random data to write to the stream.
array<Byte>^dataArray = gcnew array<Byte>(arrayLength);
(gcnew Random)->NextBytes( dataArray );
BinaryWriter^ binWriter = gcnew BinaryWriter( gcnew MemoryStream );
// Write the data to the stream.
Console::WriteLine( "Writing the data." );
binWriter->Write( dataArray );
// Create the reader using the stream from the writer.
BinaryReader^ binReader = gcnew BinaryReader( binWriter->BaseStream );
// Set the stream position to the beginning of the stream.
binReader->BaseStream->Position = 0;
// Read and verify the data.
array<Byte>^verifyArray = binReader->ReadBytes( arrayLength );
if ( verifyArray->Length != arrayLength )
{
Console::WriteLine( "Error writing the data." );
return -1;
}
for ( int i = 0; i < arrayLength; i++ )
{
if ( verifyArray[ i ] != dataArray[ i ] )
{
Console::WriteLine( "Error writing the data." );
return -1;
}
}
Console::WriteLine( "The data was written and verified." );
}
using System;
using System.IO;
class BinaryRW
{
static void Main()
{
const int arrayLength = 1000;
// Create random data to write to the stream.
byte[] dataArray = new byte[arrayLength];
new Random().NextBytes(dataArray);
BinaryWriter binWriter = new BinaryWriter(new MemoryStream());
// Write the data to the stream.
Console.WriteLine("Writing the data.");
binWriter.Write(dataArray);
// Create the reader using the stream from the writer.
BinaryReader binReader =
new BinaryReader(binWriter.BaseStream);
// Set Position to the beginning of the stream.
binReader.BaseStream.Position = 0;
// Read and verify the data.
byte[] verifyArray = binReader.ReadBytes(arrayLength);
if(verifyArray.Length != arrayLength)
{
Console.WriteLine("Error writing the data.");
return;
}
for(int i = 0; i < arrayLength; i++)
{
if(verifyArray[i] != dataArray[i])
{
Console.WriteLine("Error writing the data.");
return;
}
}
Console.WriteLine("The data was written and verified.");
}
}
open System
open System.IO
let arrayLength = 1000
// Create random data to write to the stream.
let dataArray = Array.zeroCreate<byte> arrayLength
Random().NextBytes dataArray
let binWriter = new BinaryWriter(new MemoryStream())
// Write the data to the stream.ch
printfn "Writing the data."
binWriter.Write dataArray
// Create the reader using the stream from the writer.
let binReader = new BinaryReader(binWriter.BaseStream)
// Set Position to the beginning of the stream.
binReader.BaseStream.Position <- 0
// Read and verify the data.
let verifyArray = binReader.ReadBytes arrayLength
if verifyArray.Length <> arrayLength then
printfn "Error writing the data."
else
let mutable failed = false
for i = 0 to arrayLength - 1 do
if verifyArray[i] <> dataArray[i] then
printfn "Error writing the data."
failed <- true
if not failed then
printfn "The data was written and verified."
Imports System.IO
Public Class BinaryRW
Shared Sub Main()
Const upperBound As Integer = 1000
' Create random data to write to the stream.
Dim dataArray(upperBound) As Byte
Dim randomGenerator As New Random
randomGenerator.NextBytes(dataArray)
Dim binWriter As New BinaryWriter(New MemoryStream())
' Write the data to the stream.
Console.WriteLine("Writing the data.")
binWriter.Write(dataArray)
' Create the reader using the stream from the writer.
Dim binReader As New BinaryReader(binWriter.BaseStream)
' Set the stream position to the beginning of the stream.
binReader.BaseStream.Position = 0
' Read and verify the data.
Dim verifyArray() As Byte = _
binReader.ReadBytes(dataArray.Length)
If verifyArray.Length <> dataArray.Length Then
Console.WriteLine("Error writing the data.")
Return
End If
For i As Integer = 0 To upperBound
If verifyArray(i) <> dataArray(i) Then
Console.WriteLine("Error writing the data.")
Return
End If
Next i
Console.WriteLine("The data was written and verified.")
End Sub
End Class
此範例會讀取檔案的內容,並將它顯示為傾印文字給控制台。 從 傳回ReadBytes的陣列長度為零時,會偵測正在讀取的Byte檔案結尾。
using System;
using System.IO;
using System.Text;
public class DumpFileSample
{
private static readonly int CHUNK_SIZE = 1024;
public static void Main(String[] args)
{
if ((args.Length == 0) || !File.Exists(args[0]))
{
Console.WriteLine("Please provide an existing file name.");
}
else
{
using (FileStream fs = new FileStream(args[0], FileMode.Open, FileAccess.Read))
{
using (BinaryReader br = new BinaryReader(fs, new ASCIIEncoding()))
{
byte[] chunk;
chunk = br.ReadBytes(CHUNK_SIZE);
while(chunk.Length > 0)
{
DumpBytes(chunk, chunk.Length);
chunk = br.ReadBytes(CHUNK_SIZE);
}
}
}
}
}
public static void DumpBytes(byte[] bdata, int len)
{
int i;
int j = 0;
char dchar;
// 3 * 16 chars for hex display, 16 chars for text and 8 chars
// for the 'gutter' int the middle.
StringBuilder dumptext = new StringBuilder(" ", 16 * 4 + 8);
for (i = 0; i < len; i++)
{
dumptext.Insert(j * 3, String.Format("{0:X2} ", (int)bdata[i]));
dchar = (char)bdata[i];
//' replace 'non-printable' chars with a '.'.
if (Char.IsWhiteSpace(dchar) || Char.IsControl(dchar))
{
dchar = '.';
}
dumptext.Append(dchar);
j++;
if (j == 16)
{
Console.WriteLine(dumptext);
dumptext.Length = 0;
dumptext.Append(" ");
j = 0;
}
}
// display the remaining line
if (j > 0)
{
for (i = j; i < 16; i++)
{
dumptext.Insert(j * 3, " ");
}
Console.WriteLine(dumptext);
}
}
}
open System
open System.IO
open System.Text
let CHUNK_SIZE = 1024
let dumpBytes (bdata: byte[]) len =
let mutable j = 0
// 3 * 16 chars for hex display, 16 chars for text and 8 chars
// for the 'gutter' int the middle.
let dumptext = StringBuilder(" ", 16 * 4 + 8)
for i = 0 to len - 1 do
dumptext.Insert(j * 3, $"{int bdata[i]:X2} ") |> ignore
let dchar = char bdata[i]
//' replace 'non-printable' chars with a '.'.
let dchar =
if Char.IsWhiteSpace dchar || Char.IsControl dchar then
'.'
else
dchar
dumptext.Append dchar |> ignore
j <- j + 1
if j = 16 then
printfn $"{dumptext}"
dumptext.Length <- 0
dumptext.Append " " |> ignore
j <- 0
// display the remaining line
if j > 0 then
for i = j to 15 do
dumptext.Insert(j * 3, " ") |> ignore
printfn $"{dumptext}"
[<EntryPoint>]
let main args =
if args.Length = 0 || File.Exists args[0] |> not then
printfn "Please provide an existing file name."
else
use fs = new FileStream(args[0], FileMode.Open, FileAccess.Read)
use br = new BinaryReader(fs, ASCIIEncoding())
let mutable chunk = br.ReadBytes CHUNK_SIZE
while chunk.Length > 0 do
dumpBytes chunk chunk.Length
chunk <- br.ReadBytes CHUNK_SIZE
0
Imports System.IO
Imports System.Text
Module Module1
Private ReadOnly CHUNK_SIZE As Integer = 1024
Public Sub Main(args() As String)
If ((args.Length = 0) OrElse Not File.Exists(args(0))) Then
Console.WriteLine("Please provide an existing file name.")
Else
Using fs As FileStream = New FileStream(args(0), FileMode.Open, FileAccess.Read)
Using br As New BinaryReader(fs, New ASCIIEncoding())
Dim chunk(CHUNK_SIZE) As Byte
chunk = br.ReadBytes(CHUNK_SIZE)
While chunk.Length > 0
DumpBytes(chunk, chunk.Length)
chunk = br.ReadBytes(CHUNK_SIZE)
End While
End Using
End Using
End If
End Sub
Public Sub DumpBytes(bdata() As Byte, len As Integer)
Dim i As Integer
Dim j As Integer = 0
Dim dchar As Char
' 3 * 16 chars for hex display, 16 chars for text and 8 chars
' for the 'gutter' int the middle.
Dim dumptext As New StringBuilder(" ", 16 * 4 + 8)
For i = 0 To len - 1
dumptext.Insert(j * 3, String.Format("{0:X2} ", CType(bdata(i), Integer)))
dchar = Convert.ToChar(bdata(i))
' replace 'non-printable' chars with a '.'.
If Char.IsWhiteSpace(dchar) Or Char.IsControl(dchar) Then
dchar = "."
End If
dumptext.Append(dchar)
j += 1
If j = 16 Then
Console.WriteLine(dumptext)
dumptext.Length = 0
dumptext.Append(" ")
j = 0
End If
Next i
' display the remaining line
If j > 0 Then
' add blank hex spots to align the 'gutter'.
For i = j To 15
dumptext.Insert(j * 3, " ")
Next i
Console.WriteLine(dumptext)
End If
End Sub
End Module
備註
BinaryReader 不會在失敗的讀取作業之後還原檔案位置。
如需一般 I/O 工作的清單,請參閱 一般 I/O 工作。