BinaryWriter.Write Метод

Определение

Выполняет запись значения в текущий поток.

Перегрузки

Write(Char[], Int32, Int32)

Выполняет запись части массива символов в текущий поток и изменяет текущую позицию в потоке в соответствии с используемой Encoding и, возможно, количеством символов, записанных в поток.

Write(Byte[], Int32, Int32)

Выполняет запись части массива байтов в текущий поток.

Write(UInt64)

Записывает целое число без знака размером 8 байт в текущий поток и перемещает позицию в потоке вперед на восемь байт.

Write(UInt32)

Записывает целое число без знака размером 4 байта в текущий поток и перемещает позицию в потоке вперед на четыре байта.

Write(UInt16)

Записывает целое число без знака размером 2 байта в текущий поток и перемещает позицию в потоке вперед на два байта.

Write(String)

Записывает в текущий поток строку, предваряемую ее длиной, используя текущую кодировку BinaryWriter, и перемещает позицию в потоке вперед в соответствии с используемой кодировкой и количеством записанных в поток символов.

Write(Single)

Записывает число с плавающей запятой длиной 4 байта в текущий поток и перемещает позицию в потоке вперед на четыре байта.

Write(SByte)

Записывает байт со знаком в текущий поток и перемещает позицию в потоке вперед на один байт.

Write(ReadOnlySpan<Char>)

Записывает диапазон символов в текущий поток и изменяет текущую позицию в потоке в соответствии с используемой Encoding и, возможно, количеством символов, записанных в поток.

Write(ReadOnlySpan<Byte>)

Записывает диапазон байтов в текущий поток.

Write(Int64)

Записывает целое число со знаком размером 8 байт в текущий поток и перемещает позицию в потоке вперед на восемь байт.

Write(Char[])

Выполняет запись массива символов в текущий поток и перемещает текущую позицию в потоке в соответствии с используемой Encoding и количеством записанных в поток символов.

Write(Int16)

Записывает целое число со знаком размером 2 байта в текущий поток и перемещает позицию в потоке вперед на два байта.

Write(Half)

Записывает двухбайтовое значение с плавающей запятой в текущий поток и перемещает позицию потока на два байта.

Write(Double)

Записывает число с плавающей запятой размером 8 байт в текущий поток и перемещает позицию в потоке вперед на восемь байт.

Write(Decimal)

Записывает десятичное число в текущий поток и перемещает позицию в потоке на шестнадцать байтов.

Write(Char)

Выполняет запись символа Юникод в текущий поток и перемещает текущую позицию в потоке вперед в соответствии с используемой Encoding и количеством записанных в поток символов.

Write(Byte[])

Записывает массив байтов в базовый поток.

Write(Byte)

Выполняет запись байта без знака в текущий поток и перемещает позицию в потоке на один байт вперед.

Write(Boolean)

Записывает значение типа Boolean длиной один байт в текущий поток, при этом 0 соответствует значению false, а 1 — значению true.

Write(Int32)

Записывает четырехбайтовое целое число со знаком в текущий поток и перемещает позицию в потоке на четыре байта вперед.

Write(Char[], Int32, Int32)

Исходный код:
BinaryWriter.cs
Исходный код:
BinaryWriter.cs
Исходный код:
BinaryWriter.cs

Выполняет запись части массива символов в текущий поток и изменяет текущую позицию в потоке в соответствии с используемой Encoding и, возможно, количеством символов, записанных в поток.

public:
 virtual void Write(cli::array <char> ^ chars, int index, int count);
public virtual void Write (char[] chars, int index, int count);
abstract member Write : char[] * int * int -> unit
override this.Write : char[] * int * int -> unit
Public Overridable Sub Write (chars As Char(), index As Integer, count As Integer)

Параметры

chars
Char[]

Массив символов, содержащий записываемые в поток данные.

index
Int32

Индекс первого символа для чтения из chars и для записи в поток.

count
Int32

Количество символов для чтения из chars и для записи в поток.

Исключения

Длина буфера минус index меньше count.

chars имеет значение null.

index или count является отрицательным значением.

Ошибка ввода-вывода.

Поток закрыт.

Примеры

В следующем примере кода показано, как считывать и записывать данные с помощью памяти в качестве резервного хранилища.

using namespace System;
using namespace System::IO;
int main()
{
   array<Char>^invalidPathChars = Path::InvalidPathChars;
   MemoryStream^ memStream = gcnew MemoryStream;
   BinaryWriter^ binWriter = gcnew BinaryWriter( memStream );
   
   // Write to memory.
   binWriter->Write( "Invalid file path characters are: " );
   binWriter->Write( Path::InvalidPathChars, 0, Path::InvalidPathChars->Length );
   
   // Create the reader using the same MemoryStream 
   // as used with the writer.
   BinaryReader^ binReader = gcnew BinaryReader( memStream );
   
   // Set Position to the beginning of the stream.
   binReader->BaseStream->Position = 0;
   
   // Read the data from memory and write it to the console.
   Console::Write( binReader->ReadString() );
   int arraySize = (int)(memStream->Length - memStream->Position);
   array<Char>^memoryData = gcnew array<Char>(arraySize);
   binReader->Read( memoryData, 0, arraySize );
   Console::WriteLine( memoryData );
}
using System;
using System.IO;

class BinaryRW
{
    static void Main()
    {
        char[] invalidPathChars = Path.InvalidPathChars;
        MemoryStream memStream = new MemoryStream();
        BinaryWriter binWriter = new BinaryWriter(memStream);

        // Write to memory.
        binWriter.Write("Invalid file path characters are: ");
        binWriter.Write(
            Path.InvalidPathChars, 0, Path.InvalidPathChars.Length);

        // Create the reader using the same MemoryStream
        // as used with the writer.
        BinaryReader binReader = new BinaryReader(memStream);

        // Set Position to the beginning of the stream.
        memStream.Position = 0;

        // Read the data from memory and write it to the console.
        Console.Write(binReader.ReadString());
        int arraySize = (int)(memStream.Length - memStream.Position);
        char[] memoryData = new char[arraySize];
        binReader.Read(memoryData, 0, arraySize);
        Console.WriteLine(memoryData);
    }
}
open System.IO

let invalidPathChars = Path.GetInvalidPathChars()
let memStream = new MemoryStream()
let binWriter = new BinaryWriter(memStream)

// Write to memory.
binWriter.Write "Invalid file path characters are: "
binWriter.Write(invalidPathChars, 0, invalidPathChars.Length)

// Create the reader using the same MemoryStream
// as used with the writer.
let binReader = new BinaryReader(memStream)

// Set Position to the beginning of the stream.
memStream.Position <- 0

// Read the data from memory and write it to the console.
printf $"{binReader.ReadString()}"
let arraySize = memStream.Length - memStream.Position |> int
let memoryData = Array.zeroCreate<char> arraySize
binReader.Read(memoryData, 0, arraySize) |> ignore
printfn $"{memoryData}"
Imports System.IO

Public Class BinaryRW

    Shared Sub Main()
    
        Dim invalidPathChars() As Char = Path.InvalidPathChars
        Dim memStream As new MemoryStream()
        Dim binWriter As New BinaryWriter(memStream)

        ' Write to memory.
        binWriter.Write("Invalid file path characters are: ")
        binWriter.Write(Path.InvalidPathChars, 0, _
            Path.InvalidPathChars.Length)

        ' Create the reader using the same MemoryStream 
        ' as used with the writer.
        Dim binReader As New BinaryReader(memStream)

        ' Set Position to the beginning of the stream.
        memStream.Position = 0

        ' Read the data from memory and write it to the console.
        Console.Write(binReader.ReadString())
        Dim upperBound As Integer = _
            CInt(memStream.Length - memStream.Position) - 1
        Dim memoryData(upperBound) As Char
        binReader.Read(memoryData, 0, upperBound)
        Console.WriteLine(memoryData)
    
    End Sub
End Class

Комментарии

Список распространенных задач ввода-вывода см. в разделе Общие задачи ввода-вывода.

См. также раздел

Применяется к

Write(Byte[], Int32, Int32)

Исходный код:
BinaryWriter.cs
Исходный код:
BinaryWriter.cs
Исходный код:
BinaryWriter.cs

Выполняет запись части массива байтов в текущий поток.

public:
 virtual void Write(cli::array <System::Byte> ^ buffer, int index, int count);
public virtual void Write (byte[] buffer, int index, int count);
abstract member Write : byte[] * int * int -> unit
override this.Write : byte[] * int * int -> unit
Public Overridable Sub Write (buffer As Byte(), index As Integer, count As Integer)

Параметры

buffer
Byte[]

Массив байтов, содержащий записываемые в поток данные.

index
Int32

Индекс первого байта для чтения из buffer и для записи в поток.

count
Int32

Количество байтов для чтения из buffer и для записи в поток.

Исключения

Длина буфера минус index меньше count.

buffer имеет значение null.

index или count является отрицательным значением.

Ошибка ввода-вывода.

Поток закрыт.

Примеры

В следующем примере кода показано, как записать двоичные данные, используя память в качестве резервного хранилища, а затем проверить правильность записи данных.

using System;
using System.IO;

namespace BinaryRW
{
    class Program
    {
        static void Main(string[] args)
        {
            const int arrayLength = 1000;
            byte[] dataArray = new byte[arrayLength];
            byte[] verifyArray = new byte[arrayLength];

            new Random().NextBytes(dataArray);

            using (BinaryWriter binWriter = new BinaryWriter(new MemoryStream()))
            {
                Console.WriteLine("Writing the data.");
                binWriter.Write(dataArray, 0, arrayLength);

                using (BinaryReader binReader = new BinaryReader(binWriter.BaseStream))
                {
                    binReader.BaseStream.Position = 0;

                    if (binReader.Read(verifyArray, 0, arrayLength) != 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
let dataArray = Array.zeroCreate<byte> arrayLength
let verifyArray = Array.zeroCreate<byte> arrayLength

Random().NextBytes dataArray

do
    use binWriter = new BinaryWriter(new MemoryStream())
    printfn "Writing the data."
    binWriter.Write(dataArray, 0, arrayLength)

    use binReader = new BinaryReader(binWriter.BaseStream)
    binReader.BaseStream.Position <- 0

    if binReader.Read(verifyArray, 0, arrayLength) <> arrayLength then
        printfn "Error writing the data."
    else
        for i = 0 to arrayLength - 1 do
            if verifyArray[i] <> dataArray[i] then
                printfn "Error writing the data."
            else
                printfn "The data was written and verified."
Imports System.IO

Module Module1

    Sub Main()
        Const upperBound As Integer = 1000
        Dim dataArray(upperBound) As Byte
        Dim verifyArray(upperBound) As Byte

        Dim randomGenerator As New Random
        randomGenerator.NextBytes(dataArray)

        Using binWriter As New BinaryWriter(New MemoryStream())
            Console.WriteLine("Writing the data.")
            binWriter.Write(dataArray, 0, dataArray.Length)

            Using binReader As New BinaryReader(binWriter.BaseStream)
                binReader.BaseStream.Position = 0

                If binReader.Read(verifyArray, 0, dataArray.Length) <> dataArray.Length Then
                    Console.WriteLine("Error writing the data.")
                    Return
                End If
            End Using
        End Using

        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 Module

Комментарии

Список распространенных задач ввода-вывода см. в разделе Общие задачи ввода-вывода.

См. также раздел

Применяется к

Write(UInt64)

Исходный код:
BinaryWriter.cs
Исходный код:
BinaryWriter.cs
Исходный код:
BinaryWriter.cs

Важно!

Этот API несовместим с CLS.

Записывает целое число без знака размером 8 байт в текущий поток и перемещает позицию в потоке вперед на восемь байт.

public:
 virtual void Write(System::UInt64 value);
[System.CLSCompliant(false)]
public virtual void Write (ulong value);
[<System.CLSCompliant(false)>]
abstract member Write : uint64 -> unit
override this.Write : uint64 -> unit
Public Overridable Sub Write (value As ULong)

Параметры

value
UInt64

Целое число без знака размером 8 байт, которое необходимо записать в поток.

Атрибуты

Исключения

Ошибка ввода-вывода.

Поток закрыт.

Комментарии

BinaryWriter сохраняет этот тип данных в малом байтовом формате.

Список распространенных задач ввода-вывода см. в разделе Общие задачи ввода-вывода.

См. также раздел

Применяется к

Write(UInt32)

Исходный код:
BinaryWriter.cs
Исходный код:
BinaryWriter.cs
Исходный код:
BinaryWriter.cs

Важно!

Этот API несовместим с CLS.

Записывает целое число без знака размером 4 байта в текущий поток и перемещает позицию в потоке вперед на четыре байта.

public:
 virtual void Write(System::UInt32 value);
[System.CLSCompliant(false)]
public virtual void Write (uint value);
[<System.CLSCompliant(false)>]
abstract member Write : uint32 -> unit
override this.Write : uint32 -> unit
Public Overridable Sub Write (value As UInteger)

Параметры

value
UInt32

Целое число без знака размером 4 байта, которое необходимо записать в поток.

Атрибуты

Исключения

Ошибка ввода-вывода.

Поток закрыт.

Комментарии

BinaryWriter сохраняет этот тип данных в малом байтовом формате.

Список распространенных задач ввода-вывода см. в разделе Общие задачи ввода-вывода.

См. также раздел

Применяется к

Write(UInt16)

Исходный код:
BinaryWriter.cs
Исходный код:
BinaryWriter.cs
Исходный код:
BinaryWriter.cs

Важно!

Этот API несовместим с CLS.

Записывает целое число без знака размером 2 байта в текущий поток и перемещает позицию в потоке вперед на два байта.

public:
 virtual void Write(System::UInt16 value);
[System.CLSCompliant(false)]
public virtual void Write (ushort value);
[<System.CLSCompliant(false)>]
abstract member Write : uint16 -> unit
override this.Write : uint16 -> unit
Public Overridable Sub Write (value As UShort)

Параметры

value
UInt16

Целое число без знака размером 2 байта, которое необходимо записать в поток.

Атрибуты

Исключения

Ошибка ввода-вывода.

Поток закрыт.

Комментарии

BinaryWriter сохраняет этот тип данных в малом байтовом формате.

Список распространенных задач ввода-вывода см. в разделе Общие задачи ввода-вывода.

См. также раздел

Применяется к

Write(String)

Исходный код:
BinaryWriter.cs
Исходный код:
BinaryWriter.cs
Исходный код:
BinaryWriter.cs

Записывает в текущий поток строку, предваряемую ее длиной, используя текущую кодировку BinaryWriter, и перемещает позицию в потоке вперед в соответствии с используемой кодировкой и количеством записанных в поток символов.

public:
 virtual void Write(System::String ^ value);
public virtual void Write (string value);
abstract member Write : string -> unit
override this.Write : string -> unit
Public Overridable Sub Write (value As String)

Параметры

value
String

Значение для записи.

Исключения

Ошибка ввода-вывода.

value имеет значение null.

Поток закрыт.

Примеры

В следующем примере кода показано, как сохранять и извлекать параметры приложения в файле .

using System;
using System.IO;
using System.Text;

class ConsoleApplication
{
    const string fileName = "AppSettings.dat";

    static void Main()
    {
        WriteDefaultValues();
        DisplayValues();
    }

    public static void WriteDefaultValues()
    {
        using (var stream = File.Open(fileName, FileMode.Create))
        {
            using (var writer = new BinaryWriter(stream, Encoding.UTF8, false))
            {
                writer.Write(1.250F);
                writer.Write(@"c:\Temp");
                writer.Write(10);
                writer.Write(true);
            }
        }
    }

    public static void DisplayValues()
    {
        float aspectRatio;
        string tempDirectory;
        int autoSaveTime;
        bool showStatusBar;

        if (File.Exists(fileName))
        {
            using (var stream = File.Open(fileName, FileMode.Open))
            {
                using (var reader = new BinaryReader(stream, Encoding.UTF8, false))
                {
                    aspectRatio = reader.ReadSingle();
                    tempDirectory = reader.ReadString();
                    autoSaveTime = reader.ReadInt32();
                    showStatusBar = reader.ReadBoolean();
                }
            }

            Console.WriteLine("Aspect ratio set to: " + aspectRatio);
            Console.WriteLine("Temp directory is: " + tempDirectory);
            Console.WriteLine("Auto save time set to: " + autoSaveTime);
            Console.WriteLine("Show status bar: " + showStatusBar);
        }
    }
}
open System.IO
open System.Text

let fileName = "AppSettings.dat"

let writeDefaultValues () =
    use stream = File.Open(fileName, FileMode.Create)
    use writer = new BinaryWriter(stream, Encoding.UTF8, false)
    writer.Write 1.250F
    writer.Write @"c:\Temp"
    writer.Write 10
    writer.Write true

let displayValues () =
    if File.Exists fileName then
        use stream = File.Open(fileName, FileMode.Open)
        use reader = new BinaryReader(stream, Encoding.UTF8, false)
        let aspectRatio = reader.ReadSingle()
        let tempDirectory = reader.ReadString()
        let autoSaveTime = reader.ReadInt32()
        let showStatusBar = reader.ReadBoolean()

        printfn $"Aspect ratio set to: {aspectRatio}"
        printfn $"Temp directory is: {tempDirectory}"
        printfn $"Auto save time set to: {autoSaveTime}"
        printfn $"Show status bar: {showStatusBar}"

writeDefaultValues ()
displayValues ()
Imports System.IO

Module Module1
    Const fileName As String = "AppSettings.dat"

    Sub Main()
        WriteDefaultValues()
        DisplayValues()
    End Sub

    Sub WriteDefaultValues()
        Using writer As BinaryWriter = New BinaryWriter(File.Open(fileName, FileMode.Create))
            writer.Write(1.25F)
            writer.Write("c:\Temp")
            writer.Write(10)
            writer.Write(True)
        End Using
    End Sub

    Sub DisplayValues()
        Dim aspectRatio As Single
        Dim tempDirectory As String
        Dim autoSaveTime As Integer
        Dim showStatusBar As Boolean

        If (File.Exists(fileName)) Then

            Using reader As BinaryReader = New BinaryReader(File.Open(fileName, FileMode.Open))
                aspectRatio = reader.ReadSingle()
                tempDirectory = reader.ReadString()
                autoSaveTime = reader.ReadInt32()
                showStatusBar = reader.ReadBoolean()
            End Using

            Console.WriteLine("Aspect ratio set to: " & aspectRatio)
            Console.WriteLine("Temp directory is: " & tempDirectory)
            Console.WriteLine("Auto save time set to: " & autoSaveTime)
            Console.WriteLine("Show status bar: " & showStatusBar)
        End If
    End Sub

End Module

Комментарии

С префиксом длины означает, что этот метод сначала записывает длину строки в байтах при кодировании с текущей BinaryWriter кодировкой экземпляра в поток. Это значение записывается как целое число без знака. Затем этот метод записывает это количество байтов в поток.

Например, строка "A" имеет длину 1, но при кодировании с помощью UTF-16; длина составляет 2 байта, поэтому значение, записанное в префиксе, равно 2, а 3 байта записываются в поток, включая префикс.

Список распространенных задач ввода-вывода см. в разделе Общие задачи ввода-вывода.

См. также раздел

Применяется к

Write(Single)

Исходный код:
BinaryWriter.cs
Исходный код:
BinaryWriter.cs
Исходный код:
BinaryWriter.cs

Записывает число с плавающей запятой длиной 4 байта в текущий поток и перемещает позицию в потоке вперед на четыре байта.

public:
 virtual void Write(float value);
public virtual void Write (float value);
abstract member Write : single -> unit
override this.Write : single -> unit
Public Overridable Sub Write (value As Single)

Параметры

value
Single

Число с плавающей запятой длиной 4 байта, которое необходимо записать в поток.

Исключения

Ошибка ввода-вывода.

Поток закрыт.

Примеры

В следующем примере кода показано, как сохранять и извлекать параметры приложения в файле .

using System;
using System.IO;
using System.Text;

class ConsoleApplication
{
    const string fileName = "AppSettings.dat";

    static void Main()
    {
        WriteDefaultValues();
        DisplayValues();
    }

    public static void WriteDefaultValues()
    {
        using (var stream = File.Open(fileName, FileMode.Create))
        {
            using (var writer = new BinaryWriter(stream, Encoding.UTF8, false))
            {
                writer.Write(1.250F);
                writer.Write(@"c:\Temp");
                writer.Write(10);
                writer.Write(true);
            }
        }
    }

    public static void DisplayValues()
    {
        float aspectRatio;
        string tempDirectory;
        int autoSaveTime;
        bool showStatusBar;

        if (File.Exists(fileName))
        {
            using (var stream = File.Open(fileName, FileMode.Open))
            {
                using (var reader = new BinaryReader(stream, Encoding.UTF8, false))
                {
                    aspectRatio = reader.ReadSingle();
                    tempDirectory = reader.ReadString();
                    autoSaveTime = reader.ReadInt32();
                    showStatusBar = reader.ReadBoolean();
                }
            }

            Console.WriteLine("Aspect ratio set to: " + aspectRatio);
            Console.WriteLine("Temp directory is: " + tempDirectory);
            Console.WriteLine("Auto save time set to: " + autoSaveTime);
            Console.WriteLine("Show status bar: " + showStatusBar);
        }
    }
}
open System.IO
open System.Text

let fileName = "AppSettings.dat"

let writeDefaultValues () =
    use stream = File.Open(fileName, FileMode.Create)
    use writer = new BinaryWriter(stream, Encoding.UTF8, false)
    writer.Write 1.250F
    writer.Write @"c:\Temp"
    writer.Write 10
    writer.Write true

let displayValues () =
    if File.Exists fileName then
        use stream = File.Open(fileName, FileMode.Open)
        use reader = new BinaryReader(stream, Encoding.UTF8, false)
        let aspectRatio = reader.ReadSingle()
        let tempDirectory = reader.ReadString()
        let autoSaveTime = reader.ReadInt32()
        let showStatusBar = reader.ReadBoolean()

        printfn $"Aspect ratio set to: {aspectRatio}"
        printfn $"Temp directory is: {tempDirectory}"
        printfn $"Auto save time set to: {autoSaveTime}"
        printfn $"Show status bar: {showStatusBar}"

writeDefaultValues ()
displayValues ()
Imports System.IO

Module Module1
    Const fileName As String = "AppSettings.dat"

    Sub Main()
        WriteDefaultValues()
        DisplayValues()
    End Sub

    Sub WriteDefaultValues()
        Using writer As BinaryWriter = New BinaryWriter(File.Open(fileName, FileMode.Create))
            writer.Write(1.25F)
            writer.Write("c:\Temp")
            writer.Write(10)
            writer.Write(True)
        End Using
    End Sub

    Sub DisplayValues()
        Dim aspectRatio As Single
        Dim tempDirectory As String
        Dim autoSaveTime As Integer
        Dim showStatusBar As Boolean

        If (File.Exists(fileName)) Then

            Using reader As BinaryReader = New BinaryReader(File.Open(fileName, FileMode.Open))
                aspectRatio = reader.ReadSingle()
                tempDirectory = reader.ReadString()
                autoSaveTime = reader.ReadInt32()
                showStatusBar = reader.ReadBoolean()
            End Using

            Console.WriteLine("Aspect ratio set to: " & aspectRatio)
            Console.WriteLine("Temp directory is: " & tempDirectory)
            Console.WriteLine("Auto save time set to: " & autoSaveTime)
            Console.WriteLine("Show status bar: " & showStatusBar)
        End If
    End Sub

End Module

Комментарии

BinaryWriter сохраняет этот тип данных в малом байтовом формате.

Список распространенных задач ввода-вывода см. в разделе Общие задачи ввода-вывода.

См. также раздел

Применяется к

Write(SByte)

Исходный код:
BinaryWriter.cs
Исходный код:
BinaryWriter.cs
Исходный код:
BinaryWriter.cs

Важно!

Этот API несовместим с CLS.

Записывает байт со знаком в текущий поток и перемещает позицию в потоке вперед на один байт.

public:
 virtual void Write(System::SByte value);
[System.CLSCompliant(false)]
public virtual void Write (sbyte value);
[<System.CLSCompliant(false)>]
abstract member Write : sbyte -> unit
override this.Write : sbyte -> unit
Public Overridable Sub Write (value As SByte)

Параметры

value
SByte

Байт со знаком, который необходимо записать в поток.

Атрибуты

Исключения

Ошибка ввода-вывода.

Поток закрыт.

Комментарии

Список распространенных задач ввода-вывода см. в разделе Общие задачи ввода-вывода.

См. также раздел

Применяется к

Write(ReadOnlySpan<Char>)

Исходный код:
BinaryWriter.cs
Исходный код:
BinaryWriter.cs
Исходный код:
BinaryWriter.cs

Записывает диапазон символов в текущий поток и изменяет текущую позицию в потоке в соответствии с используемой Encoding и, возможно, количеством символов, записанных в поток.

public:
 virtual void Write(ReadOnlySpan<char> chars);
public virtual void Write (ReadOnlySpan<char> chars);
abstract member Write : ReadOnlySpan<char> -> unit
override this.Write : ReadOnlySpan<char> -> unit
Public Overridable Sub Write (chars As ReadOnlySpan(Of Char))

Параметры

chars
ReadOnlySpan<Char>

Диапазон записываемых символов.

Применяется к

Write(ReadOnlySpan<Byte>)

Исходный код:
BinaryWriter.cs
Исходный код:
BinaryWriter.cs
Исходный код:
BinaryWriter.cs

Записывает диапазон байтов в текущий поток.

public:
 virtual void Write(ReadOnlySpan<System::Byte> buffer);
public virtual void Write (ReadOnlySpan<byte> buffer);
abstract member Write : ReadOnlySpan<byte> -> unit
override this.Write : ReadOnlySpan<byte> -> unit
Public Overridable Sub Write (buffer As ReadOnlySpan(Of Byte))

Параметры

buffer
ReadOnlySpan<Byte>

Диапазон записываемых байтов.

Применяется к

Write(Int64)

Исходный код:
BinaryWriter.cs
Исходный код:
BinaryWriter.cs
Исходный код:
BinaryWriter.cs

Записывает целое число со знаком размером 8 байт в текущий поток и перемещает позицию в потоке вперед на восемь байт.

public:
 virtual void Write(long value);
public virtual void Write (long value);
abstract member Write : int64 -> unit
override this.Write : int64 -> unit
Public Overridable Sub Write (value As Long)

Параметры

value
Int64

Целое число со знаком размером 8 байт, которое необходимо записать в поток.

Исключения

Ошибка ввода-вывода.

Поток закрыт.

Комментарии

BinaryWriter сохраняет этот тип данных в малом байтовом формате.

Список распространенных задач ввода-вывода см. в разделе Общие задачи ввода-вывода.

См. также раздел

Применяется к

Write(Char[])

Исходный код:
BinaryWriter.cs
Исходный код:
BinaryWriter.cs
Исходный код:
BinaryWriter.cs

Выполняет запись массива символов в текущий поток и перемещает текущую позицию в потоке в соответствии с используемой Encoding и количеством записанных в поток символов.

public:
 virtual void Write(cli::array <char> ^ chars);
public virtual void Write (char[] chars);
abstract member Write : char[] -> unit
override this.Write : char[] -> unit
Public Overridable Sub Write (chars As Char())

Параметры

chars
Char[]

Массив символов, содержащий записываемые в поток данные.

Исключения

chars имеет значение null.

Поток закрыт.

Ошибка ввода-вывода.

Примеры

В следующем примере кода показано, как считывать и записывать данные с помощью памяти в качестве резервного хранилища.

using namespace System;
using namespace System::IO;
int main()
{
   array<Char>^invalidPathChars = Path::InvalidPathChars;
   MemoryStream^ memStream = gcnew MemoryStream;
   BinaryWriter^ binWriter = gcnew BinaryWriter( memStream );
   
   // Write to memory.
   binWriter->Write( "Invalid file path characters are: " );
   binWriter->Write( Path::InvalidPathChars );
   
   // Create the reader using the same MemoryStream 
   // as used with the writer.
   BinaryReader^ binReader = gcnew BinaryReader( memStream );
   
   // Set Position to the beginning of the stream.
   binReader->BaseStream->Position = 0;
   
   // Read the data from memory and write it to the console.
   Console::Write( binReader->ReadString() );
   Console::WriteLine( binReader->ReadChars( (int)(memStream->Length - memStream->Position) ) );
}
using System;
using System.IO;

class BinaryRW
{
    static void Main()
    {
        char[] invalidPathChars = Path.InvalidPathChars;
        MemoryStream memStream = new MemoryStream();
        BinaryWriter binWriter = new BinaryWriter(memStream);

        // Write to memory.
        binWriter.Write("Invalid file path characters are: ");
        binWriter.Write(Path.InvalidPathChars);

        // Create the reader using the same MemoryStream
        // as used with the writer.
        BinaryReader binReader = new BinaryReader(memStream);

        // Set Position to the beginning of the stream.
        memStream.Position = 0;

        // Read the data from memory and write it to the console.
        Console.Write(binReader.ReadString());
        Console.WriteLine(binReader.ReadChars(
            (int)(memStream.Length - memStream.Position)));
    }
}
open System.IO

let invalidPathChars = Path.GetInvalidPathChars()
let memStream = new MemoryStream()
let binWriter = new BinaryWriter(memStream)

// Write to memory.
binWriter.Write "Invalid file path characters are: "
binWriter.Write invalidPathChars

// Create the reader using the same MemoryStream
// as used with the writer.
let binReader = new BinaryReader(memStream)

// Set Position to the beginning of the stream.
memStream.Position <- 0

// Read the data from memory and write it to the console.
printf $"{binReader.ReadString()}"
printfn $"{binReader.ReadChars(int (memStream.Length - memStream.Position))}"
Imports System.IO

Public Class BinaryRW

    Shared Sub Main()
    
        Dim invalidPathChars() As Char = Path.InvalidPathChars
        Dim memStream As new MemoryStream()
        Dim binWriter As New BinaryWriter(memStream)

        ' Write to memory.
        binWriter.Write("Invalid file path characters are: ")
        binWriter.Write(Path.InvalidPathChars)

        ' Create the reader using the same MemoryStream 
        ' as used with the writer.
        Dim binReader As New BinaryReader(memStream)

        ' Set Position to the beginning of the stream.
        memStream.Position = 0

        ' Read the data from memory and write it to the console.
        Console.Write(binReader.ReadString())
        Console.WriteLine(binReader.ReadChars( _
            CInt(memStream.Length - memStream.Position)))
    
    End Sub
End Class

Комментарии

В следующей таблице перечислены примеры других типичных или связанных задач ввода-вывода.

Действие Раздел с примером
Создание текстового файла. Практическое руководство. Запись текста в файл
Запись в текстовый файл. Практическое руководство. Запись текста в файл
Чтение из текстового файла. Практическое руководство. Чтение текста из файла
Добавление текста в файл. Практическое руководство. Открытие файла журнала и добавление в него данных

File.AppendText

FileInfo.AppendText
Получение размера файла. FileInfo.Length
Получение атрибутов файла. File.GetAttributes
Задайте атрибуты файла. File.SetAttributes
Определите, существует ли файл. File.Exists
Чтение из двоичного файла. Практическое руководство. Считывание данных из нового файла и запись в этот файл
Запись в двоичный файл. Практическое руководство. Считывание данных из нового файла и запись в этот файл

См. также раздел

Применяется к

Write(Int16)

Исходный код:
BinaryWriter.cs
Исходный код:
BinaryWriter.cs
Исходный код:
BinaryWriter.cs

Записывает целое число со знаком размером 2 байта в текущий поток и перемещает позицию в потоке вперед на два байта.

public:
 virtual void Write(short value);
public virtual void Write (short value);
abstract member Write : int16 -> unit
override this.Write : int16 -> unit
Public Overridable Sub Write (value As Short)

Параметры

value
Int16

Целое число со знаком размером 2 байта, которое необходимо записать в поток.

Исключения

Ошибка ввода-вывода.

Поток закрыт.

Комментарии

BinaryWriter сохраняет этот тип данных в малом байтовом формате.

В следующей таблице перечислены примеры других типичных или связанных задач ввода-вывода.

Действие Раздел с примером
Создание текстового файла. Практическое руководство. Запись текста в файл
Запись в текстовый файл. Практическое руководство. Запись текста в файл
Чтение из текстового файла. Практическое руководство. Чтение текста из файла
Добавление текста в файл. Практическое руководство. Открытие файла журнала и добавление в него данных

File.AppendText

FileInfo.AppendText
Получение размера файла. FileInfo.Length
Получение атрибутов файла. File.GetAttributes
Задайте атрибуты файла. File.SetAttributes
Определите, существует ли файл. File.Exists
Чтение из двоичного файла. Практическое руководство. Считывание данных из нового файла и запись в этот файл
Запись в двоичный файл. Практическое руководство. Считывание данных из нового файла и запись в этот файл

См. также раздел

Применяется к

Write(Half)

Исходный код:
BinaryWriter.cs
Исходный код:
BinaryWriter.cs
Исходный код:
BinaryWriter.cs

Записывает двухбайтовое значение с плавающей запятой в текущий поток и перемещает позицию потока на два байта.

public:
 virtual void Write(Half value);
public virtual void Write (Half value);
abstract member Write : Half -> unit
override this.Write : Half -> unit
Public Overridable Sub Write (value As Half)

Параметры

value
Half

Двухбайтовое значение с плавающей запятой для записи.

Исключения

Ошибка ввода-вывода.

Поток закрыт.

Примеры

В следующем примере кода показано, как считывать и записывать Double данные в память с помощью BinaryReader классов и BinaryWriter поверх MemoryStream класса . MemoryStream только считывает и записывает Byte данные.

using namespace System;
using namespace System::IO;
int main()
{
   int i;
   const int arrayLength = 1000;
   
   // Create random data to write to the stream.
   array<double>^dataArray = gcnew array<double>(arrayLength);
   Random^ randomGenerator = gcnew Random;
   for ( i = 0; i < arrayLength; i++ )
   {
      dataArray[ i ] = 100.1 * randomGenerator->NextDouble();

   }
   BinaryWriter^ binWriter = gcnew BinaryWriter( gcnew MemoryStream );
   try
   {
      
      // Write data to the stream.
      Console::WriteLine( "Writing data to the stream." );
      i = 0;
      for ( i = 0; i < arrayLength; i++ )
      {
         binWriter->Write( dataArray[ i ] );

      }
      
      // Create a reader using the stream from the writer.
      BinaryReader^ binReader = gcnew BinaryReader( binWriter->BaseStream );
      
      // Return to the beginning of the stream.
      binReader->BaseStream->Position = 0;
      try
      {
         
         // Read and verify the data.
         i = 0;
         Console::WriteLine( "Verifying the written data." );
         for ( i = 0; i < arrayLength; i++ )
         {
            if ( binReader->ReadDouble() != dataArray[ i ] )
            {
               Console::WriteLine( "Error writing data." );
               break;
            }

         }
         Console::WriteLine( "The data was written and verified." );
      }
      catch ( EndOfStreamException^ e ) 
      {
         Console::WriteLine( "Error writing data: {0}.", e->GetType()->Name );
      }

   }
   finally
   {
      binWriter->Close();
   }

}
using System;
using System.IO;

class BinaryRW
{
    static void Main()
    {
        int i;
        const int arrayLength = 1000;

        // Create random data to write to the stream.
        Random randomGenerator = new Random();
        double[] dataArray = new double[arrayLength];
        for(i = 0; i < arrayLength; i++)
        {
            dataArray[i] = 100.1 * randomGenerator.NextDouble();
        }

        using(BinaryWriter binWriter =
            new BinaryWriter(new MemoryStream()))
        {
            // Write the data to the stream.
            Console.WriteLine("Writing data to the stream.");
            for(i = 0; i < arrayLength; i++)
            {
                binWriter.Write(dataArray[i]);
            }

            // Create a reader using the stream from the writer.
            using(BinaryReader binReader =
                new BinaryReader(binWriter.BaseStream))
            {
                try
                {
                    // Return to the beginning of the stream.
                    binReader.BaseStream.Position = 0;

                    // Read and verify the data.
                    Console.WriteLine("Verifying the written data.");
                    for(i = 0; i < arrayLength; i++)
                    {
                        if(binReader.ReadDouble() != dataArray[i])
                        {
                            Console.WriteLine("Error writing data.");
                            break;
                        }
                    }
                    Console.WriteLine("The data was written " +
                        "and verified.");
                }
                catch(EndOfStreamException e)
                {
                    Console.WriteLine("Error writing data: {0}.",
                        e.GetType().Name);
                }
            }
        }
    }
}
open System
open System.IO

let arrayLength = 1000

// Create random data to write to the stream.
let randomGenerator = Random()
let dataArray = 
    Array.init arrayLength (fun _ -> 100.1 * randomGenerator.NextDouble())
do
    use binWriter = new BinaryWriter(new MemoryStream())
    // Write the data to the stream.
    printfn $"Writing data to the stream."
    for num in dataArray do
        binWriter.Write num

    // Create a reader using the stream from the writer.
    use binReader = new BinaryReader(binWriter.BaseStream)
    try
        // Return to the beginning of the stream.
        binReader.BaseStream.Position <- 0

        // Read and verify the data.
        printfn "Verifying the written data."
        for num in dataArray do
            if binReader.ReadDouble() <> num then
                printfn "Error writing data."
        printfn "The data was written and verified."
    with :? EndOfStreamException as e ->
        printfn $"Error writing data: {e.GetType().Name}."
Imports System.IO

Public Class BinaryRW

    Shared Sub Main()
    
        Dim i As Integer
        Const upperBound As Integer = 1000

        ' Create random data to write to the stream.
        Dim dataArray(upperBound) As Double
        Dim randomGenerator As New Random()
        For i = 0 To upperBound
            dataArray(i) = 100.1 * randomGenerator.NextDouble()
        Next i

        Dim binWriter As New BinaryWriter(New MemoryStream())
        Try

            ' Write data to the stream.
            Console.WriteLine("Writing data to the stream.")
            
            For i = 0 To upperBound
                binWriter.Write(dataArray(i))
            Next i

            ' Create a reader using the stream from the writer.
            Dim binReader As New BinaryReader(binWriter.BaseStream)

            ' Return to the beginning of the stream.
            binReader.BaseStream.Position = 0

            ' Read and verify the data.
            Try
                Console.WriteLine("Verifying the written data.")
                For i = 0 To upperBound
                    If binReader.ReadDouble() <> dataArray(i) Then
                        Console.WriteLine("Error writing data.")
                        Exit For
                    End If
                Next i
                Console.WriteLine("The data was written and verified.")
            Catch ex As EndOfStreamException
                Console.WriteLine("Error writing data: {0}.", _
                    ex.GetType().Name)
            End Try
        Finally
            binWriter.Close()
        End Try

    End Sub
End Class

Комментарии

Список распространенных задач ввода-вывода см. в разделе Общие задачи ввода-вывода.

См. также раздел

Применяется к

Write(Double)

Исходный код:
BinaryWriter.cs
Исходный код:
BinaryWriter.cs
Исходный код:
BinaryWriter.cs

Записывает число с плавающей запятой размером 8 байт в текущий поток и перемещает позицию в потоке вперед на восемь байт.

public:
 virtual void Write(double value);
public virtual void Write (double value);
abstract member Write : double -> unit
override this.Write : double -> unit
Public Overridable Sub Write (value As Double)

Параметры

value
Double

Число с плавающей запятой длиной 8 байт, которое необходимо записать в поток.

Исключения

Ошибка ввода-вывода.

Поток закрыт.

Примеры

В следующем примере кода показано, как считывать и записывать Double данные в память с помощью BinaryReader классов и BinaryWriter поверх MemoryStream класса . MemoryStream только считывает и записывает Byte данные.

using namespace System;
using namespace System::IO;
int main()
{
   int i;
   const int arrayLength = 1000;
   
   // Create random data to write to the stream.
   array<double>^dataArray = gcnew array<double>(arrayLength);
   Random^ randomGenerator = gcnew Random;
   for ( i = 0; i < arrayLength; i++ )
   {
      dataArray[ i ] = 100.1 * randomGenerator->NextDouble();

   }
   BinaryWriter^ binWriter = gcnew BinaryWriter( gcnew MemoryStream );
   try
   {
      
      // Write data to the stream.
      Console::WriteLine( "Writing data to the stream." );
      i = 0;
      for ( i = 0; i < arrayLength; i++ )
      {
         binWriter->Write( dataArray[ i ] );

      }
      
      // Create a reader using the stream from the writer.
      BinaryReader^ binReader = gcnew BinaryReader( binWriter->BaseStream );
      
      // Return to the beginning of the stream.
      binReader->BaseStream->Position = 0;
      try
      {
         
         // Read and verify the data.
         i = 0;
         Console::WriteLine( "Verifying the written data." );
         for ( i = 0; i < arrayLength; i++ )
         {
            if ( binReader->ReadDouble() != dataArray[ i ] )
            {
               Console::WriteLine( "Error writing data." );
               break;
            }

         }
         Console::WriteLine( "The data was written and verified." );
      }
      catch ( EndOfStreamException^ e ) 
      {
         Console::WriteLine( "Error writing data: {0}.", e->GetType()->Name );
      }

   }
   finally
   {
      binWriter->Close();
   }

}
using System;
using System.IO;

class BinaryRW
{
    static void Main()
    {
        int i;
        const int arrayLength = 1000;

        // Create random data to write to the stream.
        Random randomGenerator = new Random();
        double[] dataArray = new double[arrayLength];
        for(i = 0; i < arrayLength; i++)
        {
            dataArray[i] = 100.1 * randomGenerator.NextDouble();
        }

        using(BinaryWriter binWriter =
            new BinaryWriter(new MemoryStream()))
        {
            // Write the data to the stream.
            Console.WriteLine("Writing data to the stream.");
            for(i = 0; i < arrayLength; i++)
            {
                binWriter.Write(dataArray[i]);
            }

            // Create a reader using the stream from the writer.
            using(BinaryReader binReader =
                new BinaryReader(binWriter.BaseStream))
            {
                try
                {
                    // Return to the beginning of the stream.
                    binReader.BaseStream.Position = 0;

                    // Read and verify the data.
                    Console.WriteLine("Verifying the written data.");
                    for(i = 0; i < arrayLength; i++)
                    {
                        if(binReader.ReadDouble() != dataArray[i])
                        {
                            Console.WriteLine("Error writing data.");
                            break;
                        }
                    }
                    Console.WriteLine("The data was written " +
                        "and verified.");
                }
                catch(EndOfStreamException e)
                {
                    Console.WriteLine("Error writing data: {0}.",
                        e.GetType().Name);
                }
            }
        }
    }
}
open System
open System.IO

let arrayLength = 1000

// Create random data to write to the stream.
let randomGenerator = Random()
let dataArray = 
    Array.init arrayLength (fun _ -> 100.1 * randomGenerator.NextDouble())
do
    use binWriter = new BinaryWriter(new MemoryStream())
    // Write the data to the stream.
    printfn $"Writing data to the stream."
    for num in dataArray do
        binWriter.Write num

    // Create a reader using the stream from the writer.
    use binReader = new BinaryReader(binWriter.BaseStream)
    try
        // Return to the beginning of the stream.
        binReader.BaseStream.Position <- 0

        // Read and verify the data.
        printfn "Verifying the written data."
        for num in dataArray do
            if binReader.ReadDouble() <> num then
                printfn "Error writing data."
        printfn "The data was written and verified."
    with :? EndOfStreamException as e ->
        printfn $"Error writing data: {e.GetType().Name}."
Imports System.IO

Public Class BinaryRW

    Shared Sub Main()
    
        Dim i As Integer
        Const upperBound As Integer = 1000

        ' Create random data to write to the stream.
        Dim dataArray(upperBound) As Double
        Dim randomGenerator As New Random()
        For i = 0 To upperBound
            dataArray(i) = 100.1 * randomGenerator.NextDouble()
        Next i

        Dim binWriter As New BinaryWriter(New MemoryStream())
        Try

            ' Write data to the stream.
            Console.WriteLine("Writing data to the stream.")
            
            For i = 0 To upperBound
                binWriter.Write(dataArray(i))
            Next i

            ' Create a reader using the stream from the writer.
            Dim binReader As New BinaryReader(binWriter.BaseStream)

            ' Return to the beginning of the stream.
            binReader.BaseStream.Position = 0

            ' Read and verify the data.
            Try
                Console.WriteLine("Verifying the written data.")
                For i = 0 To upperBound
                    If binReader.ReadDouble() <> dataArray(i) Then
                        Console.WriteLine("Error writing data.")
                        Exit For
                    End If
                Next i
                Console.WriteLine("The data was written and verified.")
            Catch ex As EndOfStreamException
                Console.WriteLine("Error writing data: {0}.", _
                    ex.GetType().Name)
            End Try
        Finally
            binWriter.Close()
        End Try

    End Sub
End Class

Комментарии

Список распространенных задач ввода-вывода см. в разделе Общие задачи ввода-вывода.

См. также раздел

Применяется к

Write(Decimal)

Исходный код:
BinaryWriter.cs
Исходный код:
BinaryWriter.cs
Исходный код:
BinaryWriter.cs

Записывает десятичное число в текущий поток и перемещает позицию в потоке на шестнадцать байтов.

public:
 virtual void Write(System::Decimal value);
public virtual void Write (decimal value);
abstract member Write : decimal -> unit
override this.Write : decimal -> unit
Public Overridable Sub Write (value As Decimal)

Параметры

value
Decimal

Десятичное значение, которое необходимо записать.

Исключения

Ошибка ввода-вывода.

Поток закрыт.

Комментарии

В следующей таблице перечислены примеры других типичных или связанных задач ввода-вывода.

Действие Раздел с примером
Создание текстового файла. Практическое руководство. Запись текста в файл
Запись в текстовый файл. Практическое руководство. Запись текста в файл
Чтение из текстового файла. Практическое руководство. Чтение текста из файла
Добавление текста в файл. Практическое руководство. Открытие файла журнала и добавление в него данных

File.AppendText

FileInfo.AppendText
Получение размера файла. FileInfo.Length
Получение атрибутов файла. File.GetAttributes
Задайте атрибуты файла. File.SetAttributes
Определите, существует ли файл. File.Exists
Чтение из двоичного файла. Практическое руководство. Считывание данных из нового файла и запись в этот файл
Запись в двоичный файл. Практическое руководство. Считывание данных из нового файла и запись в этот файл

См. также раздел

Применяется к

Write(Char)

Исходный код:
BinaryWriter.cs
Исходный код:
BinaryWriter.cs
Исходный код:
BinaryWriter.cs

Выполняет запись символа Юникод в текущий поток и перемещает текущую позицию в потоке вперед в соответствии с используемой Encoding и количеством записанных в поток символов.

public:
 virtual void Write(char ch);
public virtual void Write (char ch);
abstract member Write : char -> unit
override this.Write : char -> unit
Public Overridable Sub Write (ch As Char)

Параметры

ch
Char

Незаменяющий символ Юникода, который необходимо записать.

Исключения

Ошибка ввода-вывода.

Поток закрыт.

ch представляет собой единичный символ-заместитель.

Примеры

В следующем примере кода показано, как считывать и записывать данные с помощью памяти в качестве резервного хранилища.

using namespace System;
using namespace System::IO;
int main()
{
   int i;
   array<Char>^invalidPathChars = Path::InvalidPathChars;
   MemoryStream^ memStream = gcnew MemoryStream;
   BinaryWriter^ binWriter = gcnew BinaryWriter( memStream );
   
   // Write to memory.
   binWriter->Write( "Invalid file path characters are: " );
   for ( i = 0; i < invalidPathChars->Length; i++ )
   {
      binWriter->Write( invalidPathChars[ i ] );

   }
   
   // Create the reader using the same MemoryStream 
   // as used with the writer.
   BinaryReader^ binReader = gcnew BinaryReader( memStream );
   
   // Set Position to the beginning of the stream.
   binReader->BaseStream->Position = 0;
   
   // Read the data from memory and write it to the console.
   Console::Write( binReader->ReadString() );
   array<Char>^memoryData = gcnew array<Char>(memStream->Length - memStream->Position);
   for ( i = 0; i < memoryData->Length; i++ )
   {
      memoryData[ i ] = binReader->ReadChar();

   }
   Console::WriteLine( memoryData );
}
using System;
using System.IO;

class BinaryRW
{
    static void Main()
    {
        int i = 0;
        char[] invalidPathChars = Path.InvalidPathChars;
        MemoryStream memStream = new MemoryStream();
        BinaryWriter binWriter = new BinaryWriter(memStream);

        // Write to memory.
        binWriter.Write("Invalid file path characters are: ");
        for(i = 0; i < invalidPathChars.Length; i++)
        {
            binWriter.Write(invalidPathChars[i]);
        }

        // Create the reader using the same MemoryStream
        // as used with the writer.
        BinaryReader binReader = new BinaryReader(memStream);

        // Set Position to the beginning of the stream.
        memStream.Position = 0;

        // Read the data from memory and write it to the console.
        Console.Write(binReader.ReadString());
        char[] memoryData =
            new char[memStream.Length - memStream.Position];
        for(i = 0; i < memoryData.Length; i++)
        {
            memoryData[i] = binReader.ReadChar();
        }
        Console.WriteLine(memoryData);
    }
}
open System.IO

let invalidPathChars = Path.GetInvalidPathChars()
let memStream = new MemoryStream()
let binWriter = new BinaryWriter(memStream)

// Write to memory.
binWriter.Write "Invalid file path characters are: "
for i = 0 to invalidPathChars.Length - 1 do
    binWriter.Write invalidPathChars[i]

// Create the reader using the same MemoryStream
// as used with the writer.
let binReader = new BinaryReader(memStream)

// Set Position to the beginning of the stream.
memStream.Position <- 0

// Read the data from memory and write it to the console.
printf $"{binReader.ReadString()}"
let memoryData = Array.zeroCreate<char> (int (memStream.Length - memStream.Position))
for i = 0 to memoryData.Length - 1 do
    memoryData[i] <- binReader.ReadChar()
printfn $"{memoryData}"
Imports System.IO

Public Class BinaryRW

    Shared Sub Main()
    
        Dim i As Integer = 0
        Dim invalidPathChars() As Char = Path.InvalidPathChars
        Dim memStream As new MemoryStream()
        Dim binWriter As New BinaryWriter(memStream)

        ' Write to memory.
        binWriter.Write("Invalid file path characters are: ")
        For i = 0 To invalidPathChars.Length - 1
            binWriter.Write(invalidPathChars(i))
        Next i

        ' Create the reader using the same MemoryStream 
        ' as used with the writer.
        Dim binReader As New BinaryReader(memStream)

        ' Set Position to the beginning of the stream.
        memStream.Position = 0

        ' Read the data from memory and write it to the console.
        Console.Write(binReader.ReadString())
        Dim memoryData( _
            CInt(memStream.Length - memStream.Position) - 1) As Char
        For i = 0 To memoryData.Length - 1
            memoryData(i) = binReader.ReadChar()
        Next i
        Console.WriteLine(memoryData)
    
    End Sub
End Class

Комментарии

Из-за конфликтов форматирования данных не рекомендуется использовать этот метод со следующими кодировками:

  • UTF-7

  • ISO-2022-JP

  • ISCII

Список распространенных задач ввода-вывода см. в разделе Общие задачи ввода-вывода.

Суррогатные символы Юникода должны быть записаны как пары в одном вызове, а не по отдельности. Если требуется поддержка суррогатных пар в приложении, рассмотрите возможность использования массива символов и перегрузки Write метода.

См. также раздел

Применяется к

Write(Byte[])

Исходный код:
BinaryWriter.cs
Исходный код:
BinaryWriter.cs
Исходный код:
BinaryWriter.cs

Записывает массив байтов в базовый поток.

public:
 virtual void Write(cli::array <System::Byte> ^ buffer);
public virtual void Write (byte[] buffer);
abstract member Write : byte[] -> unit
override this.Write : byte[] -> unit
Public Overridable Sub Write (buffer As Byte())

Параметры

buffer
Byte[]

Массив байтов, содержащий записываемые в поток данные.

Исключения

Ошибка ввода-вывода.

Поток закрыт.

buffer имеет значение null.

Примеры

В следующем примере кода показано, как записать двоичные данные, используя память в качестве резервного хранилища, а затем проверить правильность записи данных.

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

Комментарии

Список распространенных задач ввода-вывода см. в разделе Общие задачи ввода-вывода.

См. также раздел

Применяется к

Write(Byte)

Исходный код:
BinaryWriter.cs
Исходный код:
BinaryWriter.cs
Исходный код:
BinaryWriter.cs

Выполняет запись байта без знака в текущий поток и перемещает позицию в потоке на один байт вперед.

public:
 virtual void Write(System::Byte value);
public virtual void Write (byte value);
abstract member Write : byte -> unit
override this.Write : byte -> unit
Public Overridable Sub Write (value As Byte)

Параметры

value
Byte

Записываемый в поток байт без знака.

Исключения

Ошибка ввода-вывода.

Поток закрыт.

Примеры

В следующем примере кода показано, как записать двоичные данные, используя память в качестве резервного хранилища, а затем проверить правильность записи данных.

using namespace System;
using namespace System::IO;
int main()
{
   int i = 0;
   
   // Create random data to write to the stream.
   array<Byte>^writeArray = gcnew array<Byte>(1000);
   (gcnew Random)->NextBytes( writeArray );
   BinaryWriter^ binWriter = gcnew BinaryWriter( gcnew MemoryStream );
   BinaryReader^ binReader = gcnew BinaryReader( binWriter->BaseStream );
   try
   {
      
      // Write the data to the stream.
      Console::WriteLine( "Writing the data." );
      for ( i = 0; i < writeArray->Length; i++ )
      {
         binWriter->Write( writeArray[ i ] );

      }
      
      // Set the stream position to the beginning of the stream.
      binReader->BaseStream->Position = 0;
      
      // Read and verify the data from the stream.
      for ( i = 0; i < writeArray->Length; i++ )
      {
         if ( binReader->ReadByte() != writeArray[ i ] )
         {
            Console::WriteLine( "Error writing the data." );
            return  -1;
         }

      }
      Console::WriteLine( "The data was written and verified." );
   }
   // Catch the EndOfStreamException and write an error message.
   catch ( EndOfStreamException^ e ) 
   {
      Console::WriteLine( "Error writing the data.\n{0}", e->GetType()->Name );
   }

}
using System;
using System.IO;

class BinaryRW
{
    static void Main()
    {
        int i = 0;

        // Create random data to write to the stream.
        byte[] writeArray = new byte[1000];
        new Random().NextBytes(writeArray);

        BinaryWriter binWriter = new BinaryWriter(new MemoryStream());
        BinaryReader binReader =
            new BinaryReader(binWriter.BaseStream);

        try
        {
            // Write the data to the stream.
            Console.WriteLine("Writing the data.");
            for(i = 0; i < writeArray.Length; i++)
            {
                binWriter.Write(writeArray[i]);
            }

            // Set the stream position to the beginning of the stream.
            binReader.BaseStream.Position = 0;

            // Read and verify the data from the stream.
            for(i = 0; i < writeArray.Length; i++)
            {
                if(binReader.ReadByte() != writeArray[i])
                {
                    Console.WriteLine("Error writing the data.");
                    return;
                }
            }
            Console.WriteLine("The data was written and verified.");
        }

        // Catch the EndOfStreamException and write an error message.
        catch(EndOfStreamException e)
        {
            Console.WriteLine("Error writing the data.\n{0}",
                e.GetType().Name);
        }
    }
}
open System
open System.IO

// Create random data to write to the stream.
let writeArray = Array.zeroCreate<byte> 1000
Random().NextBytes writeArray

let binWriter = new BinaryWriter(new MemoryStream())
let binReader = new BinaryReader(binWriter.BaseStream)

try
    // Write the data to the stream.
    printfn "Writing the data."
    for i = 0 to writeArray.Length - 1 do
        binWriter.Write writeArray[i]

    // Set the stream position to the beginning of the stream.
    binReader.BaseStream.Position <- 0

    let mutable failed = false
    // Read and verify the data from the stream.
    for i = 0 to writeArray.Length - 1 do
        if binReader.ReadByte() <> writeArray[i] then
            printfn "Error writing the data."
            failed <- true
    if not failed then
        printfn "The data was written and verified."

// Catch the EndOfStreamException and write an error message.
with :? EndOfStreamException as e ->
    printfn $"Error writing the data.\n{e.GetType().Name}"
Imports System.IO

Public Class BinaryRW

    Shared Sub Main()
    
        Dim i As Integer = 0

        ' Create random data to write to the stream.
        Dim writeArray(1000) As Byte
        Dim randomGenerator As New Random()
        randomGenerator.NextBytes(writeArray)

        Dim binWriter As New BinaryWriter(New MemoryStream())
        Dim binReader As New BinaryReader(binWriter.BaseStream)

        Try
        
            ' Write the data to the stream.
            Console.WriteLine("Writing the data.")
            For i = 0 To writeArray.Length - 1
                binWriter.Write(writeArray(i))
            Next i

            ' Set the stream position to the beginning of the stream.
            binReader.BaseStream.Position = 0

            ' Read and verify the data from the stream.
            For i = 0 To writeArray.Length - 1
                If binReader.ReadByte() <> writeArray(i) Then
                    Console.WriteLine("Error writing the data.")
                    Return
                End If
            Next i
            Console.WriteLine("The data was written and verified.")

        ' Catch the EndOfStreamException and write an error message.
        Catch ex As EndOfStreamException
            Console.WriteLine("Error writing the data: {0}", _
                ex.GetType().Name)
        End Try
    
    End Sub
End Class

Комментарии

Из-за конфликтов форматирования данных не рекомендуется использовать этот метод со следующими кодировками:

  • UTF-7

  • ISO-2022-JP

  • ISCII

Список распространенных задач ввода-вывода см. в разделе Общие задачи ввода-вывода.

См. также раздел

Применяется к

Write(Boolean)

Исходный код:
BinaryWriter.cs
Исходный код:
BinaryWriter.cs
Исходный код:
BinaryWriter.cs

Записывает значение типа Boolean длиной один байт в текущий поток, при этом 0 соответствует значению false, а 1 — значению true.

public:
 virtual void Write(bool value);
public virtual void Write (bool value);
abstract member Write : bool -> unit
override this.Write : bool -> unit
Public Overridable Sub Write (value As Boolean)

Параметры

value
Boolean

Записываемое в поток значение типа Boolean (0 или 1).

Исключения

Ошибка ввода-вывода.

Поток закрыт.

Примеры

В следующем примере кода показано, как сохранять и извлекать параметры приложения в файле .

using System;
using System.IO;
using System.Text;

class ConsoleApplication
{
    const string fileName = "AppSettings.dat";

    static void Main()
    {
        WriteDefaultValues();
        DisplayValues();
    }

    public static void WriteDefaultValues()
    {
        using (var stream = File.Open(fileName, FileMode.Create))
        {
            using (var writer = new BinaryWriter(stream, Encoding.UTF8, false))
            {
                writer.Write(1.250F);
                writer.Write(@"c:\Temp");
                writer.Write(10);
                writer.Write(true);
            }
        }
    }

    public static void DisplayValues()
    {
        float aspectRatio;
        string tempDirectory;
        int autoSaveTime;
        bool showStatusBar;

        if (File.Exists(fileName))
        {
            using (var stream = File.Open(fileName, FileMode.Open))
            {
                using (var reader = new BinaryReader(stream, Encoding.UTF8, false))
                {
                    aspectRatio = reader.ReadSingle();
                    tempDirectory = reader.ReadString();
                    autoSaveTime = reader.ReadInt32();
                    showStatusBar = reader.ReadBoolean();
                }
            }

            Console.WriteLine("Aspect ratio set to: " + aspectRatio);
            Console.WriteLine("Temp directory is: " + tempDirectory);
            Console.WriteLine("Auto save time set to: " + autoSaveTime);
            Console.WriteLine("Show status bar: " + showStatusBar);
        }
    }
}
open System.IO
open System.Text

let fileName = "AppSettings.dat"

let writeDefaultValues () =
    use stream = File.Open(fileName, FileMode.Create)
    use writer = new BinaryWriter(stream, Encoding.UTF8, false)
    writer.Write 1.250F
    writer.Write @"c:\Temp"
    writer.Write 10
    writer.Write true

let displayValues () =
    if File.Exists fileName then
        use stream = File.Open(fileName, FileMode.Open)
        use reader = new BinaryReader(stream, Encoding.UTF8, false)
        let aspectRatio = reader.ReadSingle()
        let tempDirectory = reader.ReadString()
        let autoSaveTime = reader.ReadInt32()
        let showStatusBar = reader.ReadBoolean()

        printfn $"Aspect ratio set to: {aspectRatio}"
        printfn $"Temp directory is: {tempDirectory}"
        printfn $"Auto save time set to: {autoSaveTime}"
        printfn $"Show status bar: {showStatusBar}"

writeDefaultValues ()
displayValues ()
Imports System.IO

Module Module1
    Const fileName As String = "AppSettings.dat"

    Sub Main()
        WriteDefaultValues()
        DisplayValues()
    End Sub

    Sub WriteDefaultValues()
        Using writer As BinaryWriter = New BinaryWriter(File.Open(fileName, FileMode.Create))
            writer.Write(1.25F)
            writer.Write("c:\Temp")
            writer.Write(10)
            writer.Write(True)
        End Using
    End Sub

    Sub DisplayValues()
        Dim aspectRatio As Single
        Dim tempDirectory As String
        Dim autoSaveTime As Integer
        Dim showStatusBar As Boolean

        If (File.Exists(fileName)) Then

            Using reader As BinaryReader = New BinaryReader(File.Open(fileName, FileMode.Open))
                aspectRatio = reader.ReadSingle()
                tempDirectory = reader.ReadString()
                autoSaveTime = reader.ReadInt32()
                showStatusBar = reader.ReadBoolean()
            End Using

            Console.WriteLine("Aspect ratio set to: " & aspectRatio)
            Console.WriteLine("Temp directory is: " & tempDirectory)
            Console.WriteLine("Auto save time set to: " & autoSaveTime)
            Console.WriteLine("Show status bar: " & showStatusBar)
        End If
    End Sub

End Module

Комментарии

Список распространенных задач ввода-вывода см. в разделе Общие задачи ввода-вывода.

См. также раздел

Применяется к

Write(Int32)

Исходный код:
BinaryWriter.cs
Исходный код:
BinaryWriter.cs
Исходный код:
BinaryWriter.cs

Записывает четырехбайтовое целое число со знаком в текущий поток и перемещает позицию в потоке на четыре байта вперед.

public:
 virtual void Write(int value);
public virtual void Write (int value);
abstract member Write : int -> unit
override this.Write : int -> unit
Public Overridable Sub Write (value As Integer)

Параметры

value
Int32

Целое число со знаком размером 4 байта, которое необходимо записать в поток.

Исключения

Ошибка ввода-вывода.

Поток закрыт.

Примеры

В следующем примере кода показано, как сохранять и извлекать параметры приложения в файле .

using System;
using System.IO;
using System.Text;

class ConsoleApplication
{
    const string fileName = "AppSettings.dat";

    static void Main()
    {
        WriteDefaultValues();
        DisplayValues();
    }

    public static void WriteDefaultValues()
    {
        using (var stream = File.Open(fileName, FileMode.Create))
        {
            using (var writer = new BinaryWriter(stream, Encoding.UTF8, false))
            {
                writer.Write(1.250F);
                writer.Write(@"c:\Temp");
                writer.Write(10);
                writer.Write(true);
            }
        }
    }

    public static void DisplayValues()
    {
        float aspectRatio;
        string tempDirectory;
        int autoSaveTime;
        bool showStatusBar;

        if (File.Exists(fileName))
        {
            using (var stream = File.Open(fileName, FileMode.Open))
            {
                using (var reader = new BinaryReader(stream, Encoding.UTF8, false))
                {
                    aspectRatio = reader.ReadSingle();
                    tempDirectory = reader.ReadString();
                    autoSaveTime = reader.ReadInt32();
                    showStatusBar = reader.ReadBoolean();
                }
            }

            Console.WriteLine("Aspect ratio set to: " + aspectRatio);
            Console.WriteLine("Temp directory is: " + tempDirectory);
            Console.WriteLine("Auto save time set to: " + autoSaveTime);
            Console.WriteLine("Show status bar: " + showStatusBar);
        }
    }
}
open System.IO
open System.Text

let fileName = "AppSettings.dat"

let writeDefaultValues () =
    use stream = File.Open(fileName, FileMode.Create)
    use writer = new BinaryWriter(stream, Encoding.UTF8, false)
    writer.Write 1.250F
    writer.Write @"c:\Temp"
    writer.Write 10
    writer.Write true

let displayValues () =
    if File.Exists fileName then
        use stream = File.Open(fileName, FileMode.Open)
        use reader = new BinaryReader(stream, Encoding.UTF8, false)
        let aspectRatio = reader.ReadSingle()
        let tempDirectory = reader.ReadString()
        let autoSaveTime = reader.ReadInt32()
        let showStatusBar = reader.ReadBoolean()

        printfn $"Aspect ratio set to: {aspectRatio}"
        printfn $"Temp directory is: {tempDirectory}"
        printfn $"Auto save time set to: {autoSaveTime}"
        printfn $"Show status bar: {showStatusBar}"

writeDefaultValues ()
displayValues ()
Imports System.IO

Module Module1
    Const fileName As String = "AppSettings.dat"

    Sub Main()
        WriteDefaultValues()
        DisplayValues()
    End Sub

    Sub WriteDefaultValues()
        Using writer As BinaryWriter = New BinaryWriter(File.Open(fileName, FileMode.Create))
            writer.Write(1.25F)
            writer.Write("c:\Temp")
            writer.Write(10)
            writer.Write(True)
        End Using
    End Sub

    Sub DisplayValues()
        Dim aspectRatio As Single
        Dim tempDirectory As String
        Dim autoSaveTime As Integer
        Dim showStatusBar As Boolean

        If (File.Exists(fileName)) Then

            Using reader As BinaryReader = New BinaryReader(File.Open(fileName, FileMode.Open))
                aspectRatio = reader.ReadSingle()
                tempDirectory = reader.ReadString()
                autoSaveTime = reader.ReadInt32()
                showStatusBar = reader.ReadBoolean()
            End Using

            Console.WriteLine("Aspect ratio set to: " & aspectRatio)
            Console.WriteLine("Temp directory is: " & tempDirectory)
            Console.WriteLine("Auto save time set to: " & autoSaveTime)
            Console.WriteLine("Show status bar: " & showStatusBar)
        End If
    End Sub

End Module

Комментарии

BinaryWriter сохраняет этот тип данных в малом байтовом формате.

Список распространенных задач ввода-вывода см. в разделе Общие задачи ввода-вывода.

См. также раздел

Применяется к