Windows Dev Center

The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

How to: Write Text to a File 

The following code examples show how to write text to a text file.

The first example shows how to add text to an existing file. The second example shows how to create a new text file and write a string to it. Similar functionality can be provided by the WriteAllText methods.


Visual Basic users may choose to use the methods and properties provided by the My.Computer.FileSystem object for file I/O. For more information, see My.Computer.FileSystem Object.


Imports System
Imports System.IO

Class Test
    Public Shared Sub Main()
        ' Create an instance of StreamWriter to write text to a file.
        Using sw As StreamWriter = New StreamWriter("TestFile.txt")
            ' Add some text to the file.
            sw.Write("This is the ")
            sw.WriteLine("header for the file.")
            ' Arbitrary objects can also be written to the file.
            sw.Write("The date is: ")
        End Using
    End Sub
End Class

Option Explicit On 
Option Strict On
Imports System
Imports System.IO
Public Class TextToFile
    Private Const FILE_NAME As String = "MyFile.txt"
    Public Shared Sub Main()
        If File.Exists(FILE_NAME) Then
            Console.WriteLine("{0} already exists.", FILE_NAME)
        End If
        Using sw As StreamWriter = File.CreateText(FILE_NAME)
            sw.WriteLine("This is my file.")
            sw.WriteLine("I can write ints {0} or floats {1}, and so on.", 1, 4.2)
        End Using
    End Sub
End Class

See Also

Community Additions

© 2015 Microsoft