File.WriteAllLines Method (String, String(), Encoding)


Creates a new file, writes the specified string array to the file by using the specified encoding, and then closes the file.

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

Public Shared Sub WriteAllLines (
	path As String,
	contents As String(),
	encoding As Encoding


Type: System.String

The file to write to.

Type: System.String()

The string array to write to the file.

Type: System.Text.Encoding

An Encoding object that represents the character encoding applied to the string array.

Exception Condition

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


Either path or contents is null.


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.

If the target file already exists, it is overwritten.

Given a string array and a file path, this method opens the specified file, writes the string array to the file using the specified encoding, and then closes the file.

The following code example demonstrates the use of the WriteAllLines 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"}
            File.WriteAllLines(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.ReadAllLines(path, Encoding.UTF8)
        Dim s As String
        For Each s In readText
    End Sub
End Class


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

.NET Framework
Available since 2.0
Return to top