File.WriteAllText Method (String, String, Encoding)


Creates a new file, writes the specified string to the file using the specified encoding, and then closes the file. If the target file already exists, it is overwritten.

Namespace:   System.IO
Assembly:  mscorlib (in mscorlib.dll)

Public Shared Sub WriteAllText (
	path As String,
	contents As String,
	encoding As Encoding


Type: System.String

The file to write to.

Type: System.String

The string to write to the file.

Type: System.Text.Encoding

The encoding to apply to the string.

Exception Condition

path is a zero-length string, contains only white space, or contains one or more invalid characters as defined by InvalidPathChars.


path is null or contents is empty.


The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.


The specified path is invalid (for example, it is on an unmapped drive).


An I/O error occurred while opening the file.


path specified a file that is read-only.


This operation is not supported on the current platform.


path specified a directory.


The caller does not have the required permission.


path is in an invalid format.


The caller does not have the required permission.

Given a string and a file path, this method opens the specified file, writes the string to the file using the specified encoding, and then closes the file. The file handle is guaranteed to be closed by this method, even if exceptions are raised.

The following code example demonstrates the use of the WriteAllText method to write text to a file. In this example a file is created, if it doesn't already exist, and text is added to it.

Imports System
Imports System.IO
Imports System.Text

Public Class Test
    Public Shared Sub Main()
        Dim path As String = "c:\temp\MyTest.txt"
        Dim sw As StreamWriter

        ' This text is added only once to the file.
        If File.Exists(path) = False Then

            ' Create a file to write to.
            Dim createText As String = "Hello and Welcome" + Environment.NewLine
            File.WriteAllText(path, createText, Encoding.UTF8)
        End If

        ' This text is always added, making the file longer over time
        ' if it is not deleted.
        Dim appendText As String = "This is extra text" + Environment.NewLine
        File.AppendAllText(path, appendText, Encoding.UTF8)

        ' Open the file to read from.
        Dim readText As String = File.ReadAllText(path)
    End Sub
End Class


for access to write to a file or directory. Associated enumeration: FileIOPermissionAccess.Write

Universal Windows Platform
Available since 10
.NET Framework
Available since 2.0
Available since 4.0
Return to top