BinaryWriter.Write 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
會寫入一個值到目前的串流。
多載
| 名稱 | Description |
|---|---|
| Write(Char[], Int32, Int32) |
將字元陣列的一個區段寫入目前串流,並根據所用或特定字元,推進串流 |
| Write(Byte[], Int32, Int32) |
將位元組陣列的一個區域寫入目前的串流。 |
| Write(UInt64) |
將一個八位元組的無符號整數寫入當前串流,並將串流位置前進八位元組。 |
| Write(UInt32) |
將一個四位元組的無符號整數寫入目前串流,並將串流位置前進四個位元組。 |
| Write(UInt16) |
將一個兩位元組的無符號整數寫入目前串流,並將串流位置前進兩個位元組。 |
| Write(String) |
以目前 BinaryWriter編碼的編碼寫入一個長度前綴字串,並依據所用編碼及寫入串流的特定字元,推進串流的當前位置。 |
| Write(Single) |
將一個四位元組的浮點數寫入目前串流,並將串流位置前進四個位元組。 |
| Write(SByte) |
寫入一個有簽名的位元組到目前串流,並將串流位置往前推進一個位元組。 |
| Write(ReadOnlySpan<Char>) |
將一組字元寫入當前串流,並根據所用及可能的特定字元,推進串流 |
| Write(ReadOnlySpan<Byte>) |
將一段位元組寫入當前串流。 |
| Write(Int64) |
將一個八位元組的有符號整數寫入目前串流,並將串流位置前進八位元組。 |
| Write(Char[]) |
將字元陣列寫入目前串流,並根據所用及特定字元推進串流的 |
| Write(Int16) |
將一個兩位元組的有符號整數寫入目前串流,並將串流位置向前推進兩個位元組。 |
| Write(Half) |
將兩個位元組的浮點數寫入目前串流,並將串流位置前進兩個位元組。 |
| Write(Double) |
將一個八位元組的浮點數寫入目前串流,並將串流位置往前推進八個位元組。 |
| Write(Decimal) |
將小數值寫入目前串流,並將串流位置前進十六位元組。 |
| Write(Char) |
會將 Unicode 字元寫入目前串流,並根據所用及特定字元推進串流的 |
| Write(Byte[]) |
將一個位元組陣列寫入底層串流。 |
| Write(Byte) |
寫入一個未簽名的位元組到目前串流,並將串流位置往前推進一個位元組。 |
| Write(Boolean) |
會將一個位元組 |
| Write(Int32) |
寫入一個四位元組的有符號整數到目前串流,並將串流位置前進四個位元組。 |
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 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 任務的清單,請參見 Common 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 任務的清單,請參見 Common I/O 任務。
另請參閱
適用於
Write(UInt64)
重要
此 API 不符合 CLS 規範。
將一個八位元組的無符號整數寫入當前串流,並將串流位置前進八位元組。
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
寫入的八位元組無符號整數。
- 屬性
例外狀況
發生 I/O 錯誤。
溪流已經關閉。
備註
BinaryWriter 以小端序格式儲存此資料型態。
關於常見 I/O 任務的清單,請參見 Common I/O 任務。
另請參閱
適用於
Write(UInt32)
重要
此 API 不符合 CLS 規範。
將一個四位元組的無符號整數寫入目前串流,並將串流位置前進四個位元組。
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
寫入的四位元組無符號整數。
- 屬性
例外狀況
發生 I/O 錯誤。
溪流已經關閉。
備註
BinaryWriter 以小端序格式儲存此資料型態。
關於常見 I/O 任務的清單,請參見 Common I/O 任務。
另請參閱
適用於
Write(UInt16)
重要
此 API 不符合 CLS 規範。
將一個兩位元組的無符號整數寫入目前串流,並將串流位置前進兩個位元組。
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
要寫入的兩位元組無符號整數。
- 屬性
例外狀況
發生 I/O 錯誤。
溪流已經關閉。
備註
BinaryWriter 以小端序格式儲存此資料型態。
關於常見 I/O 任務的清單,請參見 Common 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
備註
長度前綴表示此方法會先將字串長度(以位元組)寫入,當將實 BinaryWriter 例目前的編碼編碼到串流時。 此值以無符號整數形式表示。 此方法接著將該數量的位元組寫入串流。
例如,字串「A」的長度為 1,但以 UTF-16 編碼時;長度為 2 位元組,因此前綴中寫入的值為 2,串流中寫入 3 位元組,包含前綴。
關於常見 I/O 任務的清單,請參見 Common I/O 任務。
另請參閱
適用於
Write(Single)
將一個四位元組的浮點數寫入目前串流,並將串流位置前進四個位元組。
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
四位元組浮點數值用來寫入。
例外狀況
發生 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 以小端序格式儲存此資料型態。
關於常見 I/O 任務的清單,請參見 Common I/O 任務。
另請參閱
適用於
Write(SByte)
重要
此 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
寫字的簽名位元組。
- 屬性
例外狀況
發生 I/O 錯誤。
溪流已經關閉。
備註
關於常見 I/O 任務的清單,請參見 Common 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)
將一個八位元組的有符號整數寫入目前串流,並將串流位置前進八位元組。
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
寫入的八位元組帶符號整數。
例外狀況
發生 I/O 錯誤。
溪流已經關閉。
備註
BinaryWriter 以小端序格式儲存此資料型態。
關於常見 I/O 任務的清單,請參見 Common 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 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)
將一個兩位元組的有符號整數寫入目前串流,並將串流位置向前推進兩個位元組。
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
兩個位元組的帶符號整數要寫入。
例外狀況
發生 I/O 錯誤。
溪流已經關閉。
備註
BinaryWriter 以小端序格式儲存此資料型態。
下表列出其他典型或相關的 I/O 任務範例。
| 若要這麼做... | 請參閱本主題中的範例... |
|---|---|
| 建立文字檔。 | 如何:將文字寫入檔案 |
| 寫入文字檔。 | 如何:將文字寫入檔案 |
| 從文字檔讀取。 | 如何:從檔案讀取文字 |
| 在檔案中附加文字。 |
如何:開啟並附加至記錄檔 File.AppendText FileInfo.AppendText |
| 拿出檔案大小。 | FileInfo.Length |
| 取得檔案的屬性。 | File.GetAttributes |
| 設定檔案的屬性。 | File.SetAttributes |
| 判斷是否有檔案存在。 | File.Exists |
| 從二進位檔案讀取。 | 如何:讀取和寫入新建立的數據檔 |
| 寫入二進位檔案。 | 如何:讀取和寫入新建立的數據檔 |
另請參閱
適用於
Write(Half)
將兩個位元組的浮點數寫入目前串流,並將串流位置前進兩個位元組。
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
要寫入的兩位元組浮點數值。
例外狀況
發生 I/O 錯誤。
溪流已經關閉。
範例
以下程式碼範例展示了如何在類別上Double方使用 BinaryReader and BinaryWriter 類別來讀寫MemoryStream資料到記憶體。
MemoryStream 只讀寫 Byte 資料。
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 任務的清單,請參見 Common I/O 任務。
另請參閱
適用於
Write(Double)
將一個八位元組的浮點數寫入目前串流,並將串流位置往前推進八個位元組。
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
用來寫入的八位元組浮點數值。
例外狀況
發生 I/O 錯誤。
溪流已經關閉。
範例
以下程式碼範例展示了如何在類別上Double方使用 BinaryReader and BinaryWriter 類別來讀寫MemoryStream資料到記憶體。
MemoryStream 只讀寫 Byte 資料。
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 任務的清單,請參見 Common I/O 任務。
另請參閱
適用於
Write(Decimal)
將小數值寫入目前串流,並將串流位置前進十六位元組。
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
要寫入的十進位值。
例外狀況
發生 I/O 錯誤。
溪流已經關閉。
備註
下表列出其他典型或相關的 I/O 任務範例。
| 若要這麼做... | 請參閱本主題中的範例... |
|---|---|
| 建立文字檔。 | 如何:將文字寫入檔案 |
| 寫入文字檔。 | 如何:將文字寫入檔案 |
| 從文字檔讀取。 | 如何:從檔案讀取文字 |
| 在檔案中附加文字。 |
如何:開啟並附加至記錄檔 File.AppendText FileInfo.AppendText |
| 拿出檔案大小。 | FileInfo.Length |
| 取得檔案的屬性。 | File.GetAttributes |
| 設定檔案的屬性。 | File.SetAttributes |
| 判斷是否有檔案存在。 | File.Exists |
| 從二進位檔案讀取。 | 如何:讀取和寫入新建立的數據檔 |
| 寫入二進位檔案。 | 如何:讀取和寫入新建立的數據檔 |
另請參閱
適用於
Write(Char)
會將 Unicode 字元寫入目前串流,並根據所用及特定字元推進串流的 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
非替代的 Unicode 字元要寫。
例外狀況
發生 I/O 錯誤。
溪流已經關閉。
ch 是一個單一的替代角色。
範例
以下程式碼範例展示了如何利用記憶體作為後備儲存來讀寫資料。
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 任務的清單,請參見 Common I/O 任務。
Unicode 代理字元必須在同一呼叫中成對寫出,而非單獨寫出。 如果你需要在應用程式中支援代理對,可以考慮使用字元陣列和 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 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 任務的清單,請參見 Common I/O 任務。
另請參閱
適用於
Write(Byte)
寫入一個未簽名的位元組到目前串流,並將串流位置往前推進一個位元組。
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 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 任務的清單,請參見 Common I/O 任務。
另請參閱
適用於
Write(Boolean)
會將一個位元組 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)。
例外狀況
發生 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 任務的清單,請參見 Common I/O 任務。
另請參閱
適用於
Write(Int32)
寫入一個四位元組的有符號整數到目前串流,並將串流位置前進四個位元組。
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
四位元組的簽名整數來寫入。
例外狀況
發生 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 以小端序格式儲存此資料型態。
關於常見 I/O 任務的清單,請參見 Common I/O 任務。