BinaryWriter.Write 메서드

정의

현재 스트림에 값을 씁니다.

오버로드

Write(Char[], Int32, Int32)

문자 배열 섹션을 현재 스트림에 쓴 다음 사용된 Encoding과 스트림에 쓰여지는 특정 문자의 길이만큼 스트림의 현재 위치를 앞으로 이동합니다.

Write(Byte[], Int32, Int32)

현재 스트림에 바이트 배열 영역을 씁니다.

Write(UInt64)

8바이트 부호 없는 정수를 현재 스트림에 쓰고 스트림 위치를 8바이트씩 앞으로 이동합니다.

Write(UInt32)

4바이트 부호 없는 정수를 현재 스트림에 쓰고 스트림 위치를 4바이트씩 앞으로 이동합니다.

Write(UInt16)

2바이트 부호 없는 정수를 현재 스트림에 쓰고 스트림 위치를 2바이트씩 앞으로 이동합니다.

Write(String)

BinaryWriter의 현재 인코딩으로 된 이 스트림에 문자열의 길이가 맨 앞에 나오는 문자열을 쓴 다음 사용된 인코딩과 스트림에 쓰여지는 특정 문자의 길이만큼 스트림의 현재 위치를 앞으로 이동합니다.

Write(Single)

4바이트 부동 소수점 값을 현재 스트림에 쓰고 스트림 위치를 4바이트씩 앞으로 이동합니다.

Write(SByte)

부호 있는 바이트를 현재 스트림에 쓰고 스트림 위치를 1바이트씩 앞으로 이동합니다.

Write(ReadOnlySpan<Char>)

문자 범위를 현재 스트림에 쓴 다음 사용된 Encoding과 스트림에 쓰여지는 특정 문자의 길이만큼 스트림의 현재 위치를 앞으로 이동합니다.

Write(ReadOnlySpan<Byte>)

현재 스트림에 바이트 범위를 씁니다.

Write(Int64)

8바이트 부호 있는 정수를 현재 스트림에 쓰고 스트림 위치를 8바이트씩 앞으로 이동합니다.

Write(Char[])

문자 배열을 현재 스트림에 쓴 다음 사용된 Encoding과 스트림에 쓰여지는 특정 문자의 길이만큼 스트림의 현재 위치를 앞으로 이동합니다.

Write(Int16)

2바이트 부호 있는 정수를 현재 스트림에 쓰고 스트림 위치를 2바이트씩 앞으로 이동합니다.

Write(Half)

2바이트 부동 소수점 값을 현재 스트림에 쓰고 스트림 위치를 2바이트로 이동합니다.

Write(Double)

8바이트 부동 소수점 값을 현재 스트림에 쓰고 스트림 위치를 8바이트씩 앞으로 이동합니다.

Write(Decimal)

10진 값을 현재 스트림에 쓰고 스트림 위치를 16바이트씩 앞으로 이동합니다.

Write(Char)

유니코드 문자를 현재 스트림에 쓴 다음 사용된 Encoding과 스트림에 쓰여지는 특정 문자의 길이만큼 스트림의 현재 위치를 앞으로 이동합니다.

Write(Byte[])

내부 스트림에 바이트 배열을 씁니다.

Write(Byte)

부호 없는 바이트를 현재 스트림에 쓰고 스트림 위치를 1바이트씩 앞으로 이동합니다.

Write(Boolean)

Boolean를 나타내는 0과 false를 나타내는 1을 사용하여 1바이트 true 값을 현재 스트림에 씁니다.

Write(Int32)

4바이트 부호 있는 정수를 현재 스트림에 쓰고 스트림 위치를 4바이트씩 앞으로 이동합니다.

Write(Char[], Int32, Int32)

문자 배열 섹션을 현재 스트림에 쓴 다음 사용된 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가 음수입니다.

I/O 오류가 발생했습니다.

스트림이 닫혔습니다.

예제

다음 코드 예제에서는 메모리를 백업 저장소로 사용하여 데이터를 읽고 쓰는 방법을 보여줍니다.

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

설명

일반적인 I/O 작업 목록은 일반적인 I/O 작업을 참조하세요.

추가 정보

적용 대상

Write(Byte[], Int32, Int32)

현재 스트림에 바이트 배열 영역을 씁니다.

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가 음수입니다.

I/O 오류가 발생했습니다.

스트림이 닫혔습니다.

예제

다음 코드 예제에서는 메모리를 백업 저장소로 사용하여 이진 데이터를 작성한 다음 데이터가 올바르게 작성되었는지 확인하는 방법을 보여 있습니다.

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

설명

일반적인 I/O 작업 목록은 일반적인 I/O 작업을 참조하세요.

추가 정보

적용 대상

Write(UInt64)

중요

이 API는 CLS 규격이 아닙니다.

8바이트 부호 없는 정수를 현재 스트림에 쓰고 스트림 위치를 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바이트 부호 없는 정수입니다.

특성

예외

I/O 오류가 발생했습니다.

스트림이 닫혔습니다.

설명

BinaryWriter 는 이 데이터 형식을 little endian 형식으로 저장합니다.

일반적인 I/O 작업 목록은 일반적인 I/O 작업을 참조하세요.

추가 정보

적용 대상

Write(UInt32)

중요

이 API는 CLS 규격이 아닙니다.

4바이트 부호 없는 정수를 현재 스트림에 쓰고 스트림 위치를 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바이트 부호 없는 정수입니다.

특성

예외

I/O 오류가 발생했습니다.

스트림이 닫혔습니다.

설명

BinaryWriter 는 이 데이터 형식을 little endian 형식으로 저장합니다.

일반적인 I/O 작업 목록은 일반적인 I/O 작업을 참조하세요.

추가 정보

적용 대상

Write(UInt16)

중요

이 API는 CLS 규격이 아닙니다.

2바이트 부호 없는 정수를 현재 스트림에 쓰고 스트림 위치를 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바이트 부호 없는 정수입니다.

특성

예외

I/O 오류가 발생했습니다.

스트림이 닫혔습니다.

설명

BinaryWriter 는 이 데이터 형식을 little endian 형식으로 저장합니다.

일반적인 I/O 작업 목록은 일반적인 I/O 작업을 참조하세요.

추가 정보

적용 대상

Write(String)

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

작성할 값입니다.

예외

I/O 오류가 발생했습니다.

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

설명

길이 접두사는 이 메서드가 스트림에 instance 현재 인코딩으로 인코딩될 때 문자열의 길이를 바이트 단위로 BinaryWriter 씁니다. 이 값은 부호 없는 정수로 작성됩니다. 그런 다음, 이 메서드는 스트림에 많은 바이트를 씁니다.

예를 들어 문자열 "A"의 길이는 1이지만 UTF-16으로 인코딩된 경우 입니다. 길이는 2바이트이므로 접두사로 작성된 값은 2이고 접두사를 포함하여 3바이트가 스트림에 기록됩니다.

일반적인 I/O 작업 목록은 일반적인 I/O 작업을 참조하세요.

추가 정보

적용 대상

Write(Single)

4바이트 부동 소수점 값을 현재 스트림에 쓰고 스트림 위치를 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바이트 부동 소수점 값입니다.

예외

I/O 오류가 발생했습니다.

스트림이 닫혔습니다.

예제

다음 코드 예제에는 저장 하 고 파일에서 애플리케이션 설정을 검색 하는 방법을 보여 줍니다.

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 는 이 데이터 형식을 little endian 형식으로 저장합니다.

일반적인 I/O 작업 목록은 일반적인 I/O 작업을 참조하세요.

추가 정보

적용 대상

Write(SByte)

중요

이 API는 CLS 규격이 아닙니다.

부호 있는 바이트를 현재 스트림에 쓰고 스트림 위치를 1바이트씩 앞으로 이동합니다.

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

쓸 부호 있는 바이트입니다.

특성

예외

I/O 오류가 발생했습니다.

스트림이 닫혔습니다.

설명

일반적인 I/O 작업 목록은 일반적인 I/O 작업을 참조하세요.

추가 정보

적용 대상

Write(ReadOnlySpan<Char>)

문자 범위를 현재 스트림에 쓴 다음 사용된 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>)

현재 스트림에 바이트 범위를 씁니다.

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)

8바이트 부호 있는 정수를 현재 스트림에 쓰고 스트림 위치를 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바이트 부호 있는 정수입니다.

예외

I/O 오류가 발생했습니다.

스트림이 닫혔습니다.

설명

BinaryWriter 는 이 데이터 형식을 little endian 형식으로 저장합니다.

일반적인 I/O 작업 목록은 일반적인 I/O 작업을 참조하세요.

추가 정보

적용 대상

Write(Char[])

문자 배열을 현재 스트림에 쓴 다음 사용된 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인 경우

스트림이 닫혔습니다.

I/O 오류가 발생했습니다.

예제

다음 코드 예제에서는 메모리를 백업 저장소로 사용하여 데이터를 읽고 쓰는 방법을 보여줍니다.

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

설명

다음 표에는 다른 일반적인 또는 관련 I/O 작업의 예가 나와 있습니다.

수행할 작업 이 항목의 예제를 참조하세요.
텍스트 파일을 만듭니다. 방법: 파일에 텍스트 쓰기
텍스트 파일에 씁니다. 방법: 파일에 텍스트 쓰기
텍스트 파일에서 읽습니다. 방법: 파일에서 텍스트 읽기
파일에 텍스트를 추가합니다. 방법: 로그 파일 열기 및 추가

File.AppendText

FileInfo.AppendText
파일의 크기를 가져옵니다. FileInfo.Length
파일의 특성을 가져옵니다. File.GetAttributes
파일의 특성을 설정합니다. File.SetAttributes
파일이 있는지 확인합니다. File.Exists
이진 파일에서 읽습니다. 방법: 새로 만든 데이터 파일 읽기 및 쓰기
이진 파일에 씁니다. 방법: 새로 만든 데이터 파일 읽기 및 쓰기

추가 정보

적용 대상

Write(Int16)

2바이트 부호 있는 정수를 현재 스트림에 쓰고 스트림 위치를 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바이트 부호 있는 정수입니다.

예외

I/O 오류가 발생했습니다.

스트림이 닫혔습니다.

설명

BinaryWriter 는 이 데이터 형식을 little endian 형식으로 저장합니다.

다음 표에는 다른 일반적인 또는 관련 I/O 작업의 예가 나와 있습니다.

수행할 작업 이 항목의 예제를 참조하세요.
텍스트 파일을 만듭니다. 방법: 파일에 텍스트 쓰기
텍스트 파일에 씁니다. 방법: 파일에 텍스트 쓰기
텍스트 파일에서 읽습니다. 방법: 파일에서 텍스트 읽기
파일에 텍스트를 추가합니다. 방법: 로그 파일 열기 및 추가

File.AppendText

FileInfo.AppendText
파일의 크기를 가져옵니다. FileInfo.Length
파일의 특성을 가져옵니다. File.GetAttributes
파일의 특성을 설정합니다. File.SetAttributes
파일이 있는지 확인합니다. File.Exists
이진 파일에서 읽습니다. 방법: 새로 만든 데이터 파일 읽기 및 쓰기
이진 파일에 씁니다. 방법: 새로 만든 데이터 파일 읽기 및 쓰기

추가 정보

적용 대상

Write(Half)

2바이트 부동 소수점 값을 현재 스트림에 쓰고 스트림 위치를 2바이트 앞으로 이동합니다.

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

쓸 2 바이트 부동 소수점 값입니다.

예외

I/O 오류가 발생했습니다.

스트림이 닫혔습니다.

예제

다음 코드 예제에서는 사용 하 여 BinaryReader 메모리에 데이터를 읽고 쓰는 Double 방법을 보여 줍니다는 및 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

설명

일반적인 I/O 작업 목록은 일반적인 I/O 작업을 참조하세요.

추가 정보

적용 대상

Write(Double)

8바이트 부동 소수점 값을 현재 스트림에 쓰고 스트림 위치를 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바이트 부동 소수점 값입니다.

예외

I/O 오류가 발생했습니다.

스트림이 닫혔습니다.

예제

다음 코드 예제에서는 사용 하 여 BinaryReader 메모리에 데이터를 읽고 쓰는 Double 방법을 보여 줍니다는 및 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

설명

일반적인 I/O 작업 목록은 일반적인 I/O 작업을 참조하세요.

추가 정보

적용 대상

Write(Decimal)

10진 값을 현재 스트림에 쓰고 스트림 위치를 16바이트씩 앞으로 이동합니다.

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

쓸 10진수 값입니다.

예외

I/O 오류가 발생했습니다.

스트림이 닫혔습니다.

설명

다음 표에는 다른 일반적인 또는 관련 I/O 작업의 예가 나와 있습니다.

수행할 작업 이 항목의 예제를 참조하세요.
텍스트 파일을 만듭니다. 방법: 파일에 텍스트 쓰기
텍스트 파일에 씁니다. 방법: 파일에 텍스트 쓰기
텍스트 파일에서 읽습니다. 방법: 파일에서 텍스트 읽기
파일에 텍스트를 추가합니다. 방법: 로그 파일 열기 및 추가

File.AppendText

FileInfo.AppendText
파일의 크기를 가져옵니다. FileInfo.Length
파일의 특성을 가져옵니다. File.GetAttributes
파일의 특성을 설정합니다. File.SetAttributes
파일이 있는지 확인합니다. File.Exists
이진 파일에서 읽습니다. 방법: 새로 만든 데이터 파일 읽기 및 쓰기
이진 파일에 씁니다. 방법: 새로 만든 데이터 파일 읽기 및 쓰기

추가 정보

적용 대상

Write(Char)

유니코드 문자를 현재 스트림에 쓴 다음 사용된 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

쓰려고 하는 서로게이트가 아닌 유니코드 문자입니다.

예외

I/O 오류가 발생했습니다.

스트림이 닫혔습니다.

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

일반적인 I/O 작업 목록은 일반적인 I/O 작업을 참조하세요.

유니코드 서로게이트 문자는 개별적으로 작성되지 않고 동일한 호출에서 함께 쌍으로 작성되어야 합니다. 애플리케이션에서 서로게이트 쌍에 대 한 지원에 필요한 경우 문자 배열을 사용 하 여 고려해 야 하며 Write 메서드 오버 로드 합니다.

추가 정보

적용 대상

Write(Byte[])

내부 스트림에 바이트 배열을 씁니다.

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[]

쓸 데이터를 포함하는 바이트 배열입니다.

예외

I/O 오류가 발생했습니다.

스트림이 닫혔습니다.

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

설명

일반적인 I/O 작업 목록은 일반적인 I/O 작업을 참조하세요.

추가 정보

적용 대상

Write(Byte)

부호 없는 바이트를 현재 스트림에 쓰고 스트림 위치를 1바이트씩 앞으로 이동합니다.

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

쓸 부호 없는 바이트입니다.

예외

I/O 오류가 발생했습니다.

스트림이 닫혔습니다.

예제

다음 코드 예제에서는 메모리를 백업 저장소로 사용하여 이진 데이터를 작성한 다음 데이터가 올바르게 기록되었는지 확인하는 방법을 보여 있습니다.

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

일반적인 I/O 작업 목록은 일반적인 I/O 작업을 참조하세요.

추가 정보

적용 대상

Write(Boolean)

Boolean를 나타내는 0과 false를 나타내는 1을 사용하여 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)입니다.

예외

I/O 오류가 발생했습니다.

스트림이 닫혔습니다.

예제

다음 코드 예제에는 저장 하 고 파일에서 애플리케이션 설정을 검색 하는 방법을 보여 줍니다.

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

설명

일반적인 I/O 작업 목록은 일반적인 I/O 작업을 참조하세요.

추가 정보

적용 대상

Write(Int32)

4바이트 부호 있는 정수를 현재 스트림에 쓰고 스트림 위치를 4바이트씩 앞으로 이동합니다.

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바이트 부호 있는 정수입니다.

예외

I/O 오류가 발생했습니다.

스트림이 닫혔습니다.

예제

다음 코드 예제에는 저장 하 고 파일에서 애플리케이션 설정을 검색 하는 방법을 보여 줍니다.

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 는 이 데이터 형식을 little endian 형식으로 저장합니다.

일반적인 I/O 작업 목록은 일반적인 I/O 작업을 참조하세요.

추가 정보

적용 대상