다음을 통해 공유


Creating a Writer

The following code example creates a writer, which is a class that can take data of some type and convert it to a byte array that can be passed to a stream.

Option Explicit On 
Option Strict On
Imports System
Imports System.IO
Public Class MyWriter
    Private s As Stream
    Public Sub New(ByVal stream As Stream)
        s = stream
    End Sub
    Public Sub WriteDouble(ByVal myData As Double)
        Dim b As Byte() = BitConverter.GetBytes(myData)
        ' GetBytes is a binary representation of a double data type.
        s.Write(b, 0, b.Length)
    End Sub
    Public Sub Close()
        s.Close()
    End Sub
End Class

[C#]
using System;
using System.IO;
public class MyWriter 
{
    private Stream s;
    public MyWriter(Stream stream) 
    {
        s = stream;
    } 
    public void WriteDouble(double myData) 
    {
        byte[] b = BitConverter.GetBytes(myData);
        // GetBytes is a binary representation of a double data type.
        s.Write(b, 0, b.Length);
    } 
    public void Close() 
    {
        s.Close();
    }
}

In this example, you create a class that has a constructor with a stream argument. From here, you can expose whatever Write methods are necessary. You must convert whatever you are writing to a byte[]. After you obtain the byte[],the Write method writes it to the stream s.

See Also

Basic File I/O | ComposingStreams