Writing Files in Visual Basic .NET

Writing files in Visual Basic .NET follows similar patterns to the ones we saw earlier for reading.

Imports System
Imports System.IO

Module Program
    Sub Main()
        ' To start, here's how to dump a string (or just bytes) into a file.
        Dim d1 As Byte() = System.Text.Encoding.UTF8.GetBytes("hello" & vbNewLine & "vb.net" & vbNewLine)
        File.WriteAllBytes("C:\temp\dat1", d1)

        ' For more granular writes, open a file for writing.
        Using f As StreamWriter = New StreamWriter("C:\temp\dat2")
            ' You can Write strings as you'd expect.
            Dim d2 As String = "some" & vbNewLine
            f.Write(d2)
            Console.WriteLine($"wrote {d2.Length} bytes")

            ' A WriteLine is also available.
            Dim n3 = f.WriteLine("writes")
            Console.WriteLine($"wrote {n3} bytes")

            ' StreamWriter provides buffered writing.
            Dim w As New StreamWriter(f.BaseStream)
            Dim n4 = w.WriteLine("buffered")
            Console.WriteLine($"wrote {n4} bytes")

            ' Use Flush to ensure all buffered operations have
            ' been applied to the underlying writer.
            w.Flush()
        End Using
    End Sub
End Module

Try running the file-writing code.

$ dotnet run
wrote 5 bytes
wrote 7 bytes
wrote 9 bytes

Then check the contents of the written files.

$ type C:\temp\dat1
hello
vb.net

$ type C:\temp\dat2
some
writes
buffered

Next we’ll look at applying some of the file I/O ideas we’ve just seen to the Console.In and Console.Out streams.

查看推荐产品

Comments powered by Disqus