및 System.IO.BinaryWriter 클래스는 System.IO.BinaryReader 문자열 이외의 데이터를 작성하고 읽는 데 사용됩니다. 다음 예제에서는 빈 파일 스트림을 만들고, 빈 파일 스트림에 데이터를 쓰고, 해당 스트림에서 데이터를 읽는 방법을 보여줍니다.
이 예제에서는 현재 디렉터리에 Test.data 라는 데이터 파일을 만들고, 연결된 BinaryWriter 개체와 BinaryReader 개체를 만들고, 개체를 사용하여 BinaryWriter 0에서 10까지의 정수를 Test.data에 씁니다. 그러면 파일 포인터가 파일 끝에 남습니다. 그런 다음 개체는 BinaryReader 파일 포인터를 원본으로 다시 설정하고 지정된 콘텐츠를 읽습니다.
비고
Test.data가 현재 디렉터리에 이미 있는 경우 예외가 IOException throw됩니다. FileMode.Create 파일 모드 옵션을 사용하여 항상 새 파일을 만들고, FileMode.CreateNew를 사용하지 않으면 예외가 발생하지 않습니다.
예시
using System;
using System.IO;
class MyStream
{
private const string FILE_NAME = "Test.data";
public static void Main()
{
if (File.Exists(FILE_NAME))
{
Console.WriteLine($"{FILE_NAME} already exists!");
return;
}
using (FileStream fs = new FileStream(FILE_NAME, FileMode.CreateNew))
{
using (BinaryWriter w = new BinaryWriter(fs))
{
for (int i = 0; i < 11; i++)
{
w.Write(i);
}
}
}
using (FileStream fs = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read))
{
using (BinaryReader r = new BinaryReader(fs))
{
for (int i = 0; i < 11; i++)
{
Console.WriteLine(r.ReadInt32());
}
}
}
}
}
// The example creates a file named "Test.data" and writes the integers 0 through 10 to it in binary format.
// It then writes the contents of Test.data to the console with each integer on a separate line.
Imports System.IO
Class MyStream
Private Const FILE_NAME As String = "Test.data"
Public Shared Sub Main()
If File.Exists(FILE_NAME) Then
Console.WriteLine($"{FILE_NAME} already exists!")
Return
End If
Using fs As New FileStream(FILE_NAME, FileMode.CreateNew)
Using w As New BinaryWriter(fs)
For i As Integer = 0 To 10
w.Write(i)
Next
End Using
End Using
Using fs As New FileStream(FILE_NAME, FileMode.Open, FileAccess.Read)
Using r As New BinaryReader(fs)
For i As Integer = 0 To 10
Console.WriteLine(r.ReadInt32())
Next
End Using
End Using
End Sub
End Class
' The example creates a file named "Test.data" and writes the integers 0 through 10 to it in binary format.
' It then writes the contents of Test.data to the console with each integer on a separate line.
참고하십시오
GitHub에서 Microsoft와 공동 작업
이 콘텐츠의 원본은 GitHub에서 찾을 수 있으며, 여기서 문제와 끌어오기 요청을 만들고 검토할 수도 있습니다. 자세한 내용은 참여자 가이드를 참조하세요.
.NET